Increment Large Integer Represented as Digits
Arrays & HashingAuto-graded · 18 test casesLast updated
Process an array of decimal digits representing a non-negative integer by adding one, correctly handling carry propagation and list expansion.
You are given an array of integers representing the digits of a non-negative whole number. The array stores digits such that the most significant digit is at index 0 and the least significant digit is at the end of the array.
Write a function to add 1 to the integer represented by the digits and return the updated sequence of digits as a list.
Assume the integer contains no leading zeros, except when representing the value 0 itself.
Constraints
1 <= len(digits) <= 1000 <= digits[i] <= 9
Examples
Example 1
Input: plus_one([1, 2, 3])
Output: [1, 2, 4]
Example 2
Input: plus_one([9, 9])
Output: [1, 0, 0]
Hints
Hint 1
Start adding from the least significant digit (the end of the list) and work backward.
Hint 2
If a digit is less than 9, incrementing it will not generate a carry, so you can stop early.
Hint 3
If all digits are 9, every digit turns to 0 and you will need to insert a leading 1 at the front.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks us to perform base-10 addition of 1 on a number whose digits are stored in an array.
We can simulate column addition starting from the rightmost position (least significant digit):
- Maintain a
carryvariable initialized to1. - Iterate backward through the array from the final index to index
0. - At each digit, calculate the sum of the digit and the current
carry. - Update the digit to
total % 10and calculate the new carry usingtotal // 10. - If
carrybecomes0, no further digits to the left need to be modified, so we can break early. - If the loop completes and
carryis still1(which occurs when every digit was9), we prepend1to the list.
To avoid modifying the input list passed by the caller, we create a copy of the list first.
Complexity
- Time Complexity: $\mathcal{O}(N)$, where $N$ is the number of digits. We iterate through the array at most once. In the worst case (all
9s), we visit every digit and insert a element at the beginning. - Space Complexity: $\mathcal{O}(N)$ space to create and return the new list of digits.
Python Solution
from typing import List
def plus_one(digits: List[int]) -> List[int]:
result = digits[:]
carry = 1
for i in range(len(result) - 1, -1, -1):
total = result[i] + carry
result[i] = total % 10
carry = total // 10
if carry == 0:
break
if carry:
result.insert(0, carry)
return result