Plus One
Easy
Topics
You are given a large integer as an array of digits digits (most significant first). Increment it by one and return the resulting digits.
Example 1
before
after
Scanning from the right, a 9 becomes 0 and the carry continues; the first non-9 absorbs it and the scan stops. The case worth naming is all nines, which needs a new leading digit and so a longer array.
Top row is the input digits; below it the incremented result.
Input: digits = [1,2,3] Output: [1,2,4]
Example 2
before
after
was 9, becomes 0
The case worth naming is all nines, which needs a new leading digit and so a longer array — as happens here.
Input: digits = [9,9] Output: [1,0,0]
Constraints
- 1 <= digits.length <= 100
- 0 <= digits[i] <= 9
- No leading zeros (except the number 0).
Editorial — intuition, approach, complexity and pitfalls
Intuition
This is grade-school addition starting from the least significant digit. A digit below 9 simply increments; a 9 becomes 0 and carries. The only special case is all 9s, which grows the number by one digit.
Approach
- Walk from the last digit toward the first.
- If the digit < 9, increment it and return — no further carry.
- If it is 9, set it to 0 and continue.
- If every digit was 9, prepend a 1.
Walkthrough
digits = [1, 9, 9]
i=2: 9 -> 0 (carry)
i=1: 9 -> 0 (carry)
i=0: 1 -> 2, return [2, 0, 0]Complexity
- Time — O(n): at most one pass over the digits.
- Space — O(1): in place, except the rare all-9s case.
Common Pitfalls
- All nines needs an extra digit. Returning the zeroed array without prepending 1 turns
[9,9]into0 0instead of1 0 0. - Return as soon as a digit below 9 is incremented. Carrying on past it would keep zeroing digits that were never part of the carry.
Full Solution — all languages
class Solution:
def plusOne(self, nums):
digits = list(nums)
for i in range(len(digits) - 1, -1, -1):
if digits[i] < 9:
digits[i] += 1
return digits
digits[i] = 0
return [1] + digitsimport java.util.*;
class Solution {
public int[] plusOne(int[] nums) {
int[] digits = nums.clone();
for (int i = digits.length - 1; i >= 0; i--) {
if (digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
int[] out = new int[digits.length + 1];
out[0] = 1;
return out;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> plusOne(vector<int>& nums) {
vector<int> digits = nums;
for (int i = (int)digits.size() - 1; i >= 0; i--) {
if (digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
digits.insert(digits.begin(), 1);
return digits;
}
};/**
* @param {number[]} nums
* @return {number[]}
*/ var plusOne = function(nums) {
const digits = nums.slice();
for (let i = digits.length - 1; i >= 0; i--) {
if (digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
return [1].concat(digits);
};
Asked at
Intuit