7. Plus One
easyAsked at UnityIncrement a large integer stored as a digit array. Unity uses this to test carry-handling on packed counters in physics state.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer. The most significant digit is first; each element contains a single digit.
Constraints
1 <= digits.length <= 1000 <= digits[i] <= 9No leading zeros except [0]
Examples
Example 1
digits=[1,2,3][1,2,4]Example 2
digits=[9,9][1,0,0]Approaches
1. Convert via BigInt
Join digits, parse to BigInt, add one, split back.
- Time
- O(n)
- Space
- O(n)
const n = BigInt(digits.join('')) + 1n;
return String(n).split('').map(Number);Tradeoff:
2. Right-to-left carry
Add one at the last digit, propagate carries while >=10. If a carry survives the loop, prepend a 1.
- Time
- O(n)
- Space
- O(1)
function plusOne(d) {
for (let i=d.length-1;i>=0;i--) {
if (d[i] < 9) { d[i]++; return d; }
d[i] = 0;
}
return [1, ...d];
}Tradeoff:
Unity-specific tips
Unity grades for branch-free arithmetic on packed counters because physics state updates run thousands of times per frame.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Plus One and other Unity interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →