top of page

'Plus One' Puzzle Break-Down in Python

Problem Statement


Increment the integer presented as an array of digits by one.



So, for instance, if we had a list of integers like the below...

digits = [1, 2, 4, 5]

... our output would be:

digits = [1, 2, 4, 6]

Where it gets slightly tricky is when dealing with nines:

digits = [9, 9, 9, 9]

Output:

digits = [1, 0, 0, 0, 0]

Now, not only do we have to possibly add an extra digit to our list, but also convert the other nines to zeroes!


Process


As always, it's best to start off problems like these with a basic outline of how you plan to approach them--ideally, you'll want to use comments.

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:

        # Start from the digit and iterate backwards
        
            # If current digit is not 9, increment it and return the list
            # If current digit is 9, set it to 0
        
        # Once we've reached the end of loop, prepend 1 to the list
        # This is because the rest of the 9's were converted to zeroes

Now, we can start filling in the blank spaces with code:

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:

        # Start from the digit and iterate backwards
        for i in range(len(digits) - 1, -1, -1):
            # If current digit is not 9, increment it and return the list
            if digits[i] < 9:
            	digits[i] += 1
            	return digits
            # If current digit is 9, set it to 0
		   digits[i] = 0

        # Once we've reached the end of loop, prepend 1 to the list
        # This is because the rest of the 9's were converted to zeroes
        return [1] + digits

*Note that, unlike with slicing strings, -1 in the context of the range function means literally -1, or the element right before element 0. That's why we start at index len(list) - 1 and stop right before (not including) -1.


Now, this code should work as intended.


Final Thoughts


If you're interested, another equally efficient way to solve this problem would be to convert the list to a string, then convert that string into an integer, add one, and then reverse that process (turning the integer back into a string, back into a list).


Thanks for reading!

I value your feedback.
Drop a line to let me know what you think.

  • LinkedIn
  • Instagram

Thanks for Reaching Out!

© 2035 Sabir Seth. All Rights Reserved.

bottom of page