InterviewPrepKit

Home / Coding / Math & Geometry

Plus One

easy Original β†—
Solving tips
  • Walk right-to-left: the first digit less than 9 can just be incremented and returned, since nothing else changes.
  • Zero out each trailing 9 as you pass it; the carry only ripples left through consecutive 9s.
  • The only case the array grows is all-nines: after the loop, prepend a leading 1 (e.g. [9,9] -> [1,0,0]).
  • Operate on the digit list directly to avoid overflow; O(n) time worst case, O(1) extra space.

Problem

You are given a non-negative integer represented as a list of its decimal digits digits, most-significant digit first. The number has no leading zeros (except the number 0 itself, given as [0]). Add one to the number and return the resulting list of digits.

Examples

  • digits = [1, 2, 3] β†’ [1, 2, 4] β€” 123 + 1 = 124.
  • digits = [4, 3, 9] β†’ [4, 4, 0] β€” 439 + 1 = 440; the trailing 9 rolls over and carries.
  • digits = [9, 9] β†’ [1, 0, 0] β€” 99 + 1 = 100; the carry propagates off the front, growing the array.

Constraints

  • 1 <= len(digits) <= 100
  • 0 <= digits[i] <= 9
  • digits has no leading zeros (aside from [0]).

Think about it first

Hint 1 Adding one only affects the end of the number, and it only keeps rippling left while it hits digits equal to 9 (which become 0 and pass a carry along).
Hint 2 Walk from the last digit toward the first. The first digit less than 9 can simply be incremented, and you're done β€” every digit to its right stays as it is.
Hint 3 The only case where the array grows is all-nines: they all become 0 and you must prepend a leading 1, turning `[9,9,9]` into `[1,0,0,0]`.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.