Plus One
Easy
ArrayMath
Problem
Given a non-negative integer represented as an array of digits (most significant first), return the array of digits representing the integer + 1.
Example 1
Input: digits = [1,2,3]
Output: [1,2,4]
Example 2
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Example 3
Input: digits = [9]
Output: [1,0]
Constraints
- 1 ≤ digits.length ≤ 100
- 0 ≤ digits[i] ≤ 9
- no leading zeros except 0 itself
Approach — Core Patterns
This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: see the walkthrough below.
Solution code
Python
class Solution:
def plusOne(self, digits):
d = digits[:]
for i in range(len(d) - 1, -1, -1):
if d[i] < 9:
d[i] += 1
return d
d[i] = 0
return [1] + d
Java
class Solution {
public int[] plusOne(int[] digits) {
for (int i = digits.length - 1; i >= 0; i--) {
if (digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
// All 9s: 999 + 1 → 1000. Need one more digit.
int[] result = new int[digits.length + 1];
result[0] = 1;
return result;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Plus One interactively → ← All solutions