This is elementary-school addition, one digit at a time: add 1 to the last digit, and only if that digit overflows past 9 does the carry ripple into the digit to its left. The only edge case is an all-9s input, where the carry ripples all the way past the front and the result grows by one digit (999 + 1 = 1000).
Convert to Integer
Time O(n)Space O(n)Join the digits into a number, add one, and split it back into digits. This works cleanly in Python because integers have unlimited precision, but it’s a fragile approach in most other languages, since a 100-digit number (allowed by the constraints) would overflow any fixed-width integer type — the language’s own integer arithmetic isn’t actually built for numbers this large.
class Solution: def plusOne(self, digits: list[int]) -> list[int]: num = int(''.join(map(str, digits))) + 1 return [int(d) for d in str(num)]Complexity: building the string and converting back both take time proportional to the number of digits → O(n) time, O(n) space for the intermediate string/number representation.
Digit-by-Digit Carry (In Place)
OptimalTime O(n)Space O(1)Walk from the last digit to the first. If a digit is less than 9, incrementing it absorbs the +1 with no further carry — return immediately. If a digit is 9, it wraps to 0 and the carry continues to the next digit to the left. If the carry survives past the very first digit (the all-9s case), prepend a 1 — a number like 999 becomes 1000, which is one digit longer.
class Solution: def plusOne(self, 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] + digitsTracing digits = [9, 9, 9]: digits[2] = 9 → wraps to 0, carry continues. digits[1] = 9 → wraps to 0, carry continues. digits[0] = 9 → wraps to 0, carry continues. The loop exhausts every index without an early return, so the carry survived the whole array — return [1, 0, 0, 0].
Tracing digits = [1, 2, 3]: digits[2] = 3 < 9, so it becomes 4 and the function returns [1, 2, 4] immediately, without touching the other digits at all.
Complexity: at most every digit is visited once, and each visit does O(1) work → O(n) time. The array is modified in place (aside from the rare all-9s case, which allocates one new list of size n+1) → O(1) extra space in the common case.