Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Math & Geometry

Plus One

EASY✓ CHIP-TIMEDLC #66 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: A non-negative integer arrives as an array of its digits, most significant first — add exactly one to the number and hand back the digit array of the result, growing it by a digit only if the addition truly overflows.

A whole, non-negative number arrives split into its individual digits, stored in an array with the most significant digit first — the way the number would be written out by hand.

The task is to add exactly one to that number and hand back the resulting value in the same digit-array form, most significant digit still first, with no extra leading zeros anywhere.

Most additions only touch the last digit, but a trailing run of 9s can carry all the way to the front; if every single digit was a 9, the result grows by one whole new leading digit.

  • digit arrays run up to a few hundred entries long
  • each entry is a single digit, 0 through 9
  • the input never carries a leading zero on a multi-digit number
  • the output may gain one extra leading digit, never more than one
EX 01
digits = [1, 2, 3]
→ [1, 2, 4]
no carry needed
EX 02
digits = [9]
→ [1, 0]
single digit rolls over
EX 03
digits = [9, 9, 9]
→ [1, 0, 0, 0]
carry ripples through every digit

The hintstake only what you need

HINT 1 THE NUDGE

Rebuilding the whole number, adding one, and re-splitting into digits works — but only because the runtime's integers aren't fixed-width. A real fixed-width integer would overflow long before this array does, so what does the array-only version look like?

HINT 2 THE STRUCTURE

Adding one can only ever ripple through a run of trailing 9s — every digit before that run is completely untouched by the addition.

HINT 3 ONE STEP FROM THE ANSWER

Walk from the last digit backward: if a digit is below 9, increment it and stop immediately — done. If it's a 9, set it to 0 and keep walking left. If the walk falls off the front, every digit was a 9, so prepend a leading 1.

Coach's boardthe pattern, step by step

THE CARRY WALKPATTERN · CARRY FROM THE LAST DIGITdigits = [8, 9, 9, 9]
8
9
9
9
STEP 1

Digits [8,9,9,9]. Walk from the last digit — a 9 rolls to 0 and carries left, anything below 9 just absorbs the carry and stops.

STEP 1 / 6 · ← → WORK TOO

The splitstwo paces, two languages

grind/plus-one.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        result = digits[:]
        for i in range(len(result) - 1, -1, -1):
            if result[i] < 9:
                result[i] += 1
                return result
            result[i] = 0   # this digit was a 9 — roll to 0 and carry left
        return [1] + result
TIME O(N)SPACE O(1) EXTRAPYTHON · RACE PACE · 9 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED