Plus One – Solution & Complexity

1. Add from the Least Significant Digit

  • The last array element is the ones place, so addition starts there.
  • If a digit is less than 9, adding one does not create a carry.
  • In that case, update the digit and return immediately.
for i in range(len(digits) - 1, -1, -1):
    if digits[i] < 9:
        digits[i] += 1
        return digits

2. Propagate Carry Through Nines

  • A digit equal to 9 becomes 0 after adding one and carries to the next digit on the left.
  • Continue scanning left while digits are 9.
  • This mirrors elementary addition.
for i in range(len(digits) - 1, -1, -1):
    if digits[i] == 9:
        digits[i] = 0
    else:
        digits[i] += 1
        return digits

3. Handle All-Nines Input

  • If every digit was 9, the loop turns them all into 0.
  • The result needs a new leading 1.
  • For example, [9, 9] becomes [1, 0, 0].
return [1] + digits

4. Final Complete Solution

  • The algorithm mutates the input list in place when possible and only allocates a new leading digit for all-nines cases.
  • It scans from right to left once.
  • Time complexity is O(n), and extra space complexity is O(1) besides the returned list.
def plus_one(digits: list[int]) -> list[int]:
    for i in range(len(digits) - 1, -1, -1):
        if digits[i] < 9:
            digits[i] += 1
            return digits
        digits[i] = 0

    return [1] + digits

FAQ

See also: