7. Plus One
easyAsked at TeslaAdd one to a non-negative integer represented as a digit array.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
Given an array digits of a large non-negative integer (most-significant digit first), increment by one and return the result as an array. Handle carry through the array, possibly extending its length.
Constraints
1 <= digits.length <= 1000 <= digits[i] <= 9No leading zeros except for 0 itself
Examples
Example 1
Input
digits = [1,2,3]Output
[1,2,4]Example 2
Input
digits = [9,9]Output
[1,0,0]Approaches
1. BigInt convert
Stringify, BigInt+1, re-split.
- Time
- O(n)
- Space
- O(n)
return String(BigInt(digits.join('')) + 1n).split('').map(Number);Tradeoff:
2. Right-to-left carry
Walk from least-significant digit handling carry; prepend a 1 if needed.
- Time
- O(n)
- Space
- O(1)
function plusOne(digits) {
for (let i = digits.length - 1; i >= 0; i--) {
if (digits[i] < 9) { digits[i]++; return digits; }
digits[i] = 0;
}
return [1, ...digits];
}Tradeoff:
Tesla-specific tips
Tesla wants the in-place carry — avoid BigInt because embedded controllers don't have it, and the explicit loop maps cleanly to fixed-width integer math on the ECU.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.