Given a non-empty array of digits representing a non-negative integer, most significant digit first, increment the integer by one and return the resulting digit array.
Example
Input digits = [1,2,3]
Output [1,2,4]
Key Pointers
Adding one only cascades a carry when the last digit is 9 — most of the time you increment the last digit and return immediately.
Walk from the rightmost digit backward: each 9 becomes 0 and the carry moves one place left.
If every digit was 9, the carry runs off the front entirely, and a new leading 1 has to be inserted.
Step-by-Step Analysis
Walk the digits array from the last index to the first.
If the current digit is less than 9, increment it and return the array immediately.
Otherwise set the current digit to 0 and continue left, carrying the 1.
If the loop finishes (every digit was 9), prepend a 1 to the array and return it.
Complexity
Time: O(n) — Space: O(1) extra, O(n) only in the all-9s case
Code
def plusOne(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
Code Explanation
How the solution above works, piece by piece.
Add 1 from the last digit, like doing it by hand.
If the digit is less than 9, just increment it and return; nothing carries.
A 9 becomes 0 and the carry moves one digit left.
If every digit was 9, they are all 0 now: put a 1 in front ([1] + digits).
O(n) worst case, usually O(1).
Visual Walkthrough
Running it on digits = [1, 2, 3] (plus the all-9s case):
The example needs no carry: 3 becomes 4. The extra rows show the carry case (999 + 1 = 1000), handled by the same loop.