Back to Problem
Official 2140 views

Editorial: Plus One

by admin ·

5

1 Intuition

Only trailing 9s are affected by the carry.

2 Approach

Walk from the last digit: turn 9s into 0s until a digit below 9 can absorb the carry. If all digits were 9, prepend a 1.

3 Complexity Analysis

Time O(n), Space O(1) extra.

4 Solution Code

class Solution:
    def plusOne(self, digits: list[int]) -> list[int]:
        out = digits[:]
        for i in range(len(out) - 1, -1, -1):
            if out[i] < 9:
                out[i] += 1
                return out
            out[i] = 0
        return [1] + out

5 Code Walkthrough

The reference solution below implements the approach step by step.