Plus One

Easy

Topics
ArrayMath

You are given a large integer as an array of digits digits (most significant first). Increment it by one and return the resulting digits.

Example 1

before123
after124
Scanning from the right, a 9 becomes 0 and the carry continues; the first non-9 absorbs it and the scan stops. The case worth naming is all nines, which needs a new leading digit and so a longer array.
Top row is the input digits; below it the incremented result.
Input:  digits = [1,2,3]
Output: [1,2,4]

Example 2

before99
after100
was 9, becomes 0
The case worth naming is all nines, which needs a new leading digit and so a longer array — as happens here.
Input:  digits = [9,9]
Output: [1,0,0]

Constraints

  • 1 <= digits.length <= 100
  • 0 <= digits[i] <= 9
  • No leading zeros (except the number 0).
Editorial — intuition, approach, complexity and pitfalls

Intuition

This is grade-school addition starting from the least significant digit. A digit below 9 simply increments; a 9 becomes 0 and carries. The only special case is all 9s, which grows the number by one digit.

Approach

  1. Walk from the last digit toward the first.
  2. If the digit < 9, increment it and return — no further carry.
  3. If it is 9, set it to 0 and continue.
  4. If every digit was 9, prepend a 1.

Walkthrough

digits = [1, 9, 9]
i=2: 9 -> 0 (carry)
i=1: 9 -> 0 (carry)
i=0: 1 -> 2, return [2, 0, 0]

Complexity

  • Time — O(n): at most one pass over the digits.
  • Space — O(1): in place, except the rare all-9s case.

Common Pitfalls

  • All nines needs an extra digit. Returning the zeroed array without prepending 1 turns [9,9] into 0 0 instead of 1 0 0.
  • Return as soon as a digit below 9 is incremented. Carrying on past it would keep zeroing digits that were never part of the carry.

Full Solution — all languages

class Solution:
    def plusOne(self, nums):
        digits = list(nums)
        for i in range(len(digits) - 1, -1, -1):
            if digits[i] < 9:
                digits[i] += 1
                return digits
            digits[i] = 0
        return [1] + digits
Asked at Intuit
SensAI
Beta
Tap the mic to stop voice mode