Add One to Array-Represented Number
Arrays & HashingAuto-graded · 19 test casesLast updated
Tests array manipulation and carry logic when adding one to a number stored as an array of digits.
You receive an array of digits where each element holds a single digit (0-9), and the array represents a non-negative integer with the most significant digit at index 0. The number has no leading zeros unless the number itself is zero.
Write a function that adds one to this number and returns the resulting digit array.
Constraints
1 <= digits.length <= 1000 <= digits[i] <= 9- The input represents a valid non-negative integer (no leading zeros except for zero itself)
Examples
Example 1
Input: add_one_to_digits([1, 2, 3])
Output: [1, 2, 4]
Example 2
Input: add_one_to_digits([9, 9])
Output: [1, 0, 0]
Example 3
Input: add_one_to_digits([0])
Output: [1]
Hints
Hint 1
Start from the rightmost digit and work backward, just like adding by hand on paper.
Hint 2
When a digit is less than 9, you can add one and stop immediately—no carry needed.
Hint 3
If all digits are 9, the result will need one more digit at the front.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Mimic the process of addition you'd do by hand: start from the rightmost (least significant) digit and move left, handling carries as needed.
Walk through the array backward. For each digit:
- If it's less than 9, increment it by one and return immediately. No carry occurs, so digits to the left remain unchanged.
- If it's 9, set it to 0 and continue to the next digit on the left (this represents carrying 1).
If the loop completes without returning, every digit was 9 and has been set to 0. This means we've carried past all digits, so prepend 1 to the front.
Why This Works
When you add one to any number, only the rightmost sequence of 9s changes:
- Each trailing 9 becomes 0 (because 9 + 1 = 10 in that position)
- The first non-9 digit encountered increases by 1 and absorbs the carry
- All digits to the left of that position stay the same
If every digit is 9, the number is of the form 999...9, and adding one gives 1000...0, which requires one additional digit at the front.
The solution creates a copy of the input to avoid modifying the caller's array. Walking backward naturally handles the carry without needing an explicit carry variable—reaching each iteration means we have a carry to process.
Complexity
Time: O(n) where n is the length of the array. In the worst case (all 9s), we visit every digit once. For typical inputs with non-9 digits, we often stop after just one or two iterations.
Space: O(n) for the output array. The copy operation uses O(n) space. Beyond the output, we use O(1) auxiliary space.
Solution
from typing import List
def add_one_to_digits(digits: List[int]) -> List[int]:
result = digits[:]
for i in range(len(result) - 1, -1, -1):
if result[i] < 9:
result[i] += 1
return result
result[i] = 0
return [1] + result