sagelearnai

Plus One

Difficulty: Easy · Pattern: Matrix · LeetCode #66

A large integer is given as an array of its digits, most significant first, with no leading zeros. Add one and return the resulting digit array.

Examples

text
[1,2,3]  →  [1,2,4]
[4,3,2,1]  →  [4,3,2,2]
[9,9]    →  [1,0,0]

Hints

  1. Only trailing 9s are affected by the carry.

Approach

Scan from the last digit. If it's below 9, increment it and return. Otherwise set it to 0 and continue left. If every digit was 9, the answer is 1 followed by zeros ([1] + digits). O(n) worst case, but O(1) amortized over many random increments.

Complexity

Time: O(n). Space: O(1) besides the output.

Python solution
def plusOne(digits):
    digits = digits[:]
    for i in range(len(digits) - 1, -1, -1):
        if digits[i] < 9:
            digits[i] += 1
            return digits
        digits[i] = 0
    return [1] + digits
JavaScript solution
function plusOne(digits) {
  const d = [...digits];
  for (let i = d.length - 1; i >= 0; i--) {
    if (d[i] < 9) { d[i]++; return d; }
    d[i] = 0;
  }
  return [1, ...d];
}