0:00 / 0:00

Add one to a number stored as an array of digits. Start from the right, turn each 9 into 0 and carry, and grow the array if needed.

▼

The problem

LeetCode 66 (Easy). A large integer is given as an array digits, most significant digit first, with no leading zeros (1 to 100 digits). Add one and return the resulting array of digits.

Examples: LeetCode's [1,2,3] → [1,2,4] and [9] → [1,0], plus [1,2,9] → [1,3,0].

TRY IT ON LEETCODE ▶

The solution

def plusOne(digits):
    for i in range(len(digits) - 1, -1, -1):
        if digits[i] < 9:
            digits[i] += 1
            return digits
        digits[i] = 0
    return [1] + digits

Transcript

Plus One. A huge number is stored as an array of digits, most significant first. Add one, and return the new digits.

One, two, three becomes one, two, four: only the last digit changes. One, two, nine becomes one, three, zero: the nine rolls over. And nine becomes one, zero: the array grew a digit.

The easy way: join the digits into one integer, add one, and split it back. Python's big integers can do that. But the array can hold a hundred digits, and a sixty-four-bit integer holds only nineteen. In most languages, it overflows.

So add one like on paper, from the right. Picture each digit as a bucket that holds up to nine. Drip one drop into the last bucket. If it holds less than nine, the water rises by one, and we're done. If it's already full, it overflows: it empties to zero, and one drop carries to the bucket on its left.

In code, walk the index from the last digit down to the first. If the digit is below nine, add one and return right away. Otherwise it was a nine: set it to zero, and keep going left. If the loop finishes, every digit was nine, so put a one in front of the zeros.

Let's try two, four, nine, nine. The drop lands in the last nine: it overflows, becomes zero, and carries. The next nine spills too. The four catches the carry and rises to five, so we stop: two, five, zero, zero. Now nine, nine, nine. Every bucket spills, one after another. The loop ends, and a new bucket holding a one appears in front: one, zero, zero, zero.

Each digit is visited at most once, so the time is order n, when every digit is nine. Usually it stops much sooner. Extra space is order one, since the digits change in place, unless they're all nines and we need a new array.

Start at the right, spill the nines, carry the one. That's Plus One.