Plus One
Add one to a number stored as a list of digits
DSA, Easy, Math & Geometry
Which structure or algorithm, and what does it cost.
An odometer keeps its count as a list of digits, with the leftmost digit first. Each item of digits is a number from 0 to 9. The count never starts with 0, unless the count is 0 itself. Write plus_one(digits) that advances the count by 1 and returns the new digits in the same form. The count can have 200 digits, too many for a normal number type. Do not join the digits into one number. Work on the list itself.
Examples
Constraints
- 1 <= length of
digits<= 200. - Each item is a whole number from 0 to 9.
- The first item is not 0, unless the list is exactly [0].
Your answer must contain
- The simple method and why it fails with 200 digits in most languages; the better method; code; time and memory cost; a hand trace of example 1.
Target Aim for O(n) time and O(1) extra memory.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Add 1 to a long number on paper. Which digit changes first, and when does the changing stop?
Hint 2 the approach
Only a digit 9 can pass a carry on. At which end of the list does a carry start?
Hint 3 the key step
Go from the right. Add one to a digit below 9 and stop. Turn a 9 into 0 and go on. If all were 9, put a 1 in front.
Walkthrough
Full walkthrough brute force to best
Brute force
Join the digits into one number, add 1, and split the result into digits again. This is fine in a language with integers of any size, and costs O(n) time and O(n) memory. With 200 digits a 64-bit integer overflows, so in many languages it fails, and it skips the digit work the exercise is about.
Best method
Walk from the last digit to the first. If a digit is below 9, add 1 to it and return, because no carry goes further. If it is 9, it becomes 0 and the carry moves one place left. If the walk ends, every digit was 9, so the answer is a 1 followed by all zeros: put 1 in front. This is correct because only a 9 passes a carry on, and a digit below 9 absorbs it. Everything to the left of that digit stays as it was.
Hand trace
Run on [4, 7, 9]. Position 2 holds 9, so set it to 0 and carry. Position 1 holds 7, which is below 9, so make it 8 and return. The result is [4, 8, 0].
Code
def plus_one(digits):
for i in range(len(digits) - 1, -1, -1):
if digits[i] < 9:
digits[i] += 1
return digits
digits[i] = 0
return [1] + digitsTime and memory
O(n) time in the worst case, when every digit is 9. It usually stops after one or two digits. O(1) extra memory, except in the all-nines case, where the new list is one place longer.
Common mistakes
- Setting a 9 to 0 but not carrying on, so the next digit is not raised.
- Missing the all-nines case. [9, 9, 9] must become [1, 0, 0, 0], a longer list.
- Walking from left to right. The carry travels from right to left.