Plus One: Stop at the First Non-9

The problem

A non-negative integer is stored as an array of digits, most significant first. Add one and return the new array (LeetCode 66). [1,2,9] becomes [1,3,0] and [9,9] becomes [1,0,0].

The key observation

Adding one only changes a run of trailing 9s plus the digit just before them. Scan from the right: a 9 becomes 0 and the carry continues; any other digit gets incremented and you are done immediately.

def plus_one(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

The all-nines case

If the loop finishes, every digit was 9 and is now 0, so the answer is a 1 followed by those zeros. You do not need a general carry variable at all, which is what makes this solution shorter than the textbook one.

Things interviewers check

Related problems

The same right-to-left carry walk solves Add Binary, Add Strings and Plus One Linked List, where you first find the last non-9 node.


Disclosure: I work on Linkjob AI. If you want structured practice for interviews like this, AI job interview answers in real time can help you rehearse and get real-time hints.