Plus One - Problem
Problem: You're given a large integer represented as an array of digits, where each element represents one digit of the number. The digits are ordered from most significant to least significant (left-to-right), just like how we normally write numbers.
Your task is to add 1 to this number and return the result as an array of digits.
Key Points:
Example:
Your task is to add 1 to this number and return the result as an array of digits.
Key Points:
- The number has no leading zeros (except for the number 0 itself)
- You need to handle carry-over when digits become 10
- The most challenging case is when all digits are 9 (e.g., 999 + 1 = 1000)
Example:
[1,2,3] represents 123, and adding 1 gives us 124, so return [1,2,4]. Input & Output
example_1.py โ Simple Case
$
Input:
digits = [1,2,3]
โบ
Output:
[1,2,4]
๐ก Note:
The number 123 + 1 = 124. No carry needed since last digit is less than 9.
example_2.py โ Carry Required
$
Input:
digits = [4,3,2,1]
โบ
Output:
[4,3,2,2]
๐ก Note:
The number 4321 + 1 = 4322. Simple increment of last digit.
example_3.py โ All Nines Edge Case
$
Input:
digits = [9,9,9]
โบ
Output:
[1,0,0,0]
๐ก Note:
The number 999 + 1 = 1000. Carry propagates through all digits, requiring an extra digit at the front.
Visualization
Tap to expand
Understanding the Visualization
1
Start at Rightmost
Begin with the least significant digit (rightmost), just like manual addition
2
Add One
Add 1 to this digit. If result < 10, we're done!
3
Handle Carry
If result = 10, set digit to 0 and carry 1 to the next position left
4
Propagate Left
Continue carrying left until no more carry needed
5
Extra Digit
If carry remains after all digits, prepend 1 (like 999 โ 1000)
Key Takeaway
๐ฏ Key Insight: The right-to-left approach with carry propagation is optimal because most additions only affect the last digit, and when carries are needed, we handle them efficiently in a single pass.
Time & Space Complexity
Time Complexity
O(n)
Single pass through all digits, where n is the number of digits
โ Linear Growth
Space Complexity
O(1) or O(n)
O(1) if we modify input array, O(n) if we create new array for result
โก Linearithmic Space
Constraints
- 1 โค digits.length โค 100
- 0 โค digits[i] โค 9
- digits does not contain any leading zeros
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code