Plus One Solution in Python

Problem Description

Ah, the classic “Plus One” problem! It’s like that moment when you realize you’ve eaten one too many slices of pizza at a party, and now you need to account for that extra slice in your calorie count. In this LeetCode challenge, you’re given a list of digits that represent a non-negative integer. Your task? Add one to that integer and return the resulting list of digits.

For example, if you have the digits [1, 2, 3], you’re expected to return [1, 2, 4]. But if you have [9, 9, 9], well, that’s a whole different ball game, and you’ll need to return [1, 0, 0, 0]. It’s like when you’re trying to fit into your favorite jeans after the holidays—sometimes you just have to let go and start fresh!

Code Solution


class Solution:
    def plusOne(self, digits: list[int]) -> list[int]:
        for i, d in reversed(list(enumerate(digits))):
            if d < 9:
                digits[i] += 1
                return digits
            digits[i] = 0

        return [1] + digits

Approach

The approach here is straightforward yet clever. We traverse the list of digits from the end to the beginning (because who doesn’t love a good plot twist?). If we find a digit less than 9, we simply add one to it and return the list. If we encounter a 9, we turn it into a 0 and keep moving left. If we finish the loop and still have a carry (like that extra slice of pizza), we prepend a 1 to the list.

Time and Space Complexity

  • Time Complexity: O(n), where n is the number of digits in the input list. In the worst case, we might have to traverse the entire list.
  • Space Complexity: O(1), since we are modifying the input list in place and not using any additional data structures.

Real-World Example

Imagine you’re at a birthday party, and you’re counting the number of balloons. You start with 5 balloons, and then someone brings in one more. You count them up and realize you now have 6. But wait! If you had 9 balloons and someone brought in one more, you’d have to get a new bag to hold that extra balloon, right? That’s exactly what happens in the Plus One problem!