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:
  • 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
Plus One: Digital Addition VisualizationCase 1: No Carry Needed (Most Common)1hundreds2tens3ones+ 1124โœ“ Done!Case 2: Carry Required (Edge Case)999+ 1Step 1: 9+1=10 โ†’ 0, carry 10carry 1Step 2: 9+1=10 โ†’ 0, carry 100carry 1Step 3: 9+1=10 โ†’ 0, carry 1 (nowhere to go!)000carry 1Final: Prepend the carry as new digit1000โœ“ Result: 1000๐Ÿ’ก Key insight: 90% of cases need no carry, making this very efficient!
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

n
2n
โœ“ 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

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค digits.length โ‰ค 100
  • 0 โ‰ค digits[i] โ‰ค 9
  • digits does not contain any leading zeros
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
89.0K Views
High Frequency
~15 min Avg. Time
3.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen