easy

Plus One

Add one to a large number represented as an array of digits.

1. Define the problem

Plus One

You are given a large integer represented as an array of digits, where each element is a single digit and the most significant digit is first. Increment the large integer by one and return the resulting array of digits. Walk the digits from right to left , adding the carry as you go — most additions only affect the last digit, and a carry only ripples further left when a digit rolls over from 9 to 0.

Constraints

  • 1 ≤ digits.length ≤ 100
  • 0 ≤ digitsi ≤ 9
  • digits does not contain leading zeros, except the number 0 itself

Example

Inputdigits = [1, 2, 3]
Output[1, 2, 4]

Explanation The array represents 123, incrementing gives 124.

2. Know the words first

In plain terms

Carry
The extra 1 that spills over into the next digit to the left when a digit adds up to 10 or more, just like carrying a digit in long addition by hand.
3. Visualize the solution

Add one from the rightmost digit, carrying left as needed

Add one from the rightmost digit, carrying left as needed
Statusinit

i=2 (value 3). Add 1 -> 4, which is less than 10 — done, no carry.

What happens in this step

i = 2 (value 3)
digits[i] + 1 = 4

4 is less than 10, so write 4 and stop — no carry needed.
Step 1 of 4

Steps to visualize

  1. Start at the last digit of the array.
  2. Add one to that digit.
  3. If the digit is now 10, set it to 0 and move one step left to carry the extra 1.
  4. If the digit is less than 10, stop — no more carrying is needed.
  5. If the carry runs past the first digit, insert a new 1 at the front.
4. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Add one from the rightmost digit, carrying left as needed
Statusinit

i=2 (value 3). Add 1 -> 4, which is less than 10 — done, no carry.

What happens in this step

i = 2 (value 3)
digits[i] + 1 = 4

4 is less than 10, so write 4 and stop — no carry needed.
Step 1 of 4
5. Solution

Solution

solution.tsTypeScript
function plusOne(digits) {
  const result = digits.slice();

  for (let i = result.length - 1; i >= 0; i--) {
    if (result[i] < 9) {
      result[i]++;
      return result;
    }

    result[i] = 0;
  }

  return [1, ...result];
}
Time
O(n)
Space
O(n)
6. Test cases

Test cases

InputExpectedCovers
digits = [1, 2, 3][1, 2, 4]example from the docstring
digits = [1, 2, 9][1, 3, 0]a single trailing 9 rolls over and carries once
digits = [9, 9, 9][1, 0, 0, 0]every digit is 9, the result grows a new leading digit
digits = [9][1, 0]smallest valid input, a single 9 that rolls over
digits = [0][1]smallest valid input, a single digit with no carry
digits = [2, 9, 9][3, 0, 0]carry propagates through two trailing 9s and stops