Example 1
ready- Input
digits = [ 1, 2, 3 ]- Expected
[ 1, 2, 4 ]- Why
- the final digit absorbs the extra one
A calculator has the whole number. You have one decimal digit per array slot — and the number may be a hundred digits long.
Given an array digits representing a non-negative integer, add one and return the
resulting digit array. The most-significant digit—the digit with the greatest place
value—comes first.
A few ground rules:
0 through 9.[0].1 <= digits.length <= 1000 <= digits[i] <= 9digits[0] != 0 unless digits is [0].Hints
Adding one changes the last digit first. Start at the right edge, just as you would when adding numbers on paper.
If the current digit is below 9, increment it and stop. If it's 9, write 0
there and keep carrying one toward the front.
After the carry crosses the whole array, every old digit is 0. Put a new 1 at
the front.
Can you finish with constant extra space, ignoring the array you return?
Visible cases
digits = [
1,
2,
3
][
1,
2,
4
]digits = [
9
][
1,
0
]digits = [
4,
3,
2,
1
][
4,
3,
2,
2
]Interview signal
Addition wants to move from the least-significant digit—the digit in the ones
place—toward the front. Reversing a copy puts that digit at index 0, so the carry can
move forward through the copy.
def plus_one(digits: list[int]) -> list[int]:
reversed_digits = digits[::-1]
carry = 1
for i in range(len(reversed_digits)):
total = reversed_digits[i] + carry
reversed_digits[i] = total % 10
carry = total // 10
if carry == 0:
break
if carry:
reversed_digits.append(carry)
return reversed_digits[::-1]This version keeps the direction easy to see, but both reversals allocate new lists.
Time O(n) because each digit is copied or visited a constant number of times. Space O(n) for the reversed copies.
You can follow the natural right-to-left direction without reversing anything. A digit
below 9 absorbs the extra one, so you can return immediately. Only a suffix of nines
forces the carry farther left.
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] + digitsIf the loop ends, every digit was 9 and has become 0; the new leading 1 is the
final carry. Otherwise the first non-nine digit ends the work early.
Time O(n) in the all-nines case and less when the carry stops early. Space O(1) beyond the returned array.
Ready to run.
3 cases are queued.
Visible testcase
Case 1
Expected
[ 1, 2, 4 ]