SDE & MLE Prep

66. Plus One

Problem

digits holds a non-negative integer, most significant digit first, without leading zeros. Add one and return the resulting digits.

Example: [1,2,3] → [1,2,4]; [9,9] → [1,0,0]

Walk from the last digit: a 9 becomes 0 and carries; any other digit increments and we're done. All 9s → prepend 1.

Complexity: O(n).

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        for i in range(len(digits) - 1, -1, -1):
            if digits[i] < 9:
                digits[i] += 1
                return digits
            digits[i] = 0
        return [1] + digits