Plus One - Problem

You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading zeros.

Increment the large integer by one and return the resulting array of digits.

Input & Output

Example 1 — Basic Case
$ Input: digits = [1,2,3]
Output: [1,2,4]
💡 Note: The array represents 123, and 123 + 1 = 124. So we return [1,2,4].
Example 2 — Carry Required
$ Input: digits = [4,3,2,1,9]
Output: [4,3,2,2,0]
💡 Note: The array represents 43219, and 43219 + 1 = 43220. The last digit 9 becomes 0 and we carry 1.
Example 3 — All Nines
$ Input: digits = [9,9,9]
Output: [1,0,0,0]
💡 Note: The array represents 999, and 999 + 1 = 1000. We need an extra digit at the beginning.

Constraints

  • 1 ≤ digits.length ≤ 100
  • 0 ≤ digits[i] ≤ 9
  • digits does not contain any leading zeros

Visualization

Tap to expand
Plus One - Array Increment INPUT digits array (left to right) 1 index 0 2 index 1 3 index 2 Represents integer: 123 Task: Add 1 to this number 123 + 1 = ? Input Array: digits = [1, 2, 3] ALGORITHM STEPS 1 Start from right Begin at last digit (i=2) 2 Add 1 to digit digit[2]: 3 + 1 = 4 3 Check for carry If digit < 10: no carry 4 Return result 4 < 10, so done! Processing: 1 2 4 +1 Carry Logic: If digit==10: set 0, carry=1 FINAL RESULT Output array: 1 2 4 Represents integer: 124 Verification: 123 + 1 = 124 [OK] Output Array: [1, 2, 4] Key Insight: Process digits right-to-left. Add 1 to last digit. If result is 10, set to 0 and carry 1 to next digit. Special case: if all digits are 9 (e.g., [9,9,9]), prepend 1 to create [1,0,0,0]. Time: O(n), Space: O(1). TutorialsPoint - Plus One | Right-to-Left with Carry Approach
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 25
89.5K Views
High Frequency
~15 min Avg. Time
2.8K 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