← DSA
EASY

Plus One

PracticeNeetCode ↗LeetCode ↗

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

Step-by-Step Analysis

  1. Walk the digits array from the last index to the first.
  2. If the current digit is less than 9, increment it and return the array immediately.
  3. Otherwise set the current digit to 0 and continue left, carrying the 1.
  4. 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.

  1. Add 1 from the last digit, like doing it by hand.
  2. If the digit is less than 9, just increment it and return; nothing carries.
  3. A 9 becomes 0 and the carry moves one digit left.
  4. If every digit was 9, they are all 0 now: put a 1 in front ([1] + digits).
  5. O(n) worst case, usually O(1).

Visual Walkthrough

Running it on digits = [1, 2, 3] (plus the all-9s case):

trace123i=23 < 9 → becomes 4, return124result[1, 2, 4]999e.g. 999each 9 → 0 with a carry1000→all carried: prepend 1
The example needs no carry: 3 becomes 4. The extra rows show the carry case (999 + 1 = 1000), handled by the same loop.
incremented9 → 0, carryresult

Video Explanation

NeetCode — Plus One, LeetCode 66