Plus One
LeetCode 66 · Easy · solution, intuition & step-by-step walkthrough
Carry propagation from the right.
This is how I solved Plus One (LeetCode 66), an easy problem from the Other pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Add one to the last digit and propagate the carry leftwards. If the carry survives past the first digit (all nines), prepend a 1.
Approach
- 1
Add 1 to the last digit.
- 2
While there is a carry, add it to the next digit left.
- 3
Leftover carry → prepend it.
How I solved it
Carry loopPythonO(n) time
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
carry=0
n = len(digits)
last_digit=digits[n-1]
sum = last_digit+1
carry = sum//10
digits[n-1]=sum%10
r=n-2
while carry!=0 and r>=0:
sum = digits[r]+carry
carry = sum//10
digits[r]=sum%10
r-=1
if carry>0:
digits=[carry]+digits
return digitsPlus One — FAQ
What is the intuition behind Plus One?
Add one to the last digit and propagate the carry leftwards. If the carry survives past the first digit (all nines), prepend a 1.
How do you solve Plus One (LeetCode 66)?
1. Add 1 to the last digit. 2. While there is a carry, add it to the next digit left. 3. Leftover carry → prepend it.
What is the time and space complexity of Plus One?
Time: O(n). Space: O(1) (O(n) when growing). (Accepted approach: Carry loop.)
What are common mistakes in Plus One?
[9,9,9] becomes [1,0,0,0].