Skip to main content

7. Plus One

easyAsked at Quora

Increment a large integer represented as an array of digits.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

You are given a non-empty array of decimal digits representing a non-negative integer. Increment the integer by one and return the resulting digit array.

Constraints

  • 1 <= digits.length <= 100
  • 0 <= digits[i] <= 9
  • No leading zeros (except for the value 0)

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 to BigInt, add one, convert back.

Time
O(n)
Space
O(n)
const n = BigInt(digits.join('')) + 1n;
return String(n).split('').map(Number);

Tradeoff:

2. In-place carry

Walk right-to-left propagating a carry; prepend 1 if it survives.

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:

Quora-specific tips

Quora likes carry-propagation problems because their vote counters and view counters bump per-second and must overflow into wider buckets without locking the whole row.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Plus One and other Quora interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →