https://leetcode.com/problems/plus-one

How we can add 1 to given number? We need to find the biggest number of 9 in the end of our number, for example for number 5123521999235123999, there will be three 9 in the end. 5123521999235123999 + 1 = 5123521999235124000: so we need to increase previous symbol by one and change all 9 after to 0. Now, the steps of algorithm are to following:

  1. Let us add one 0 before our data to handle cases like 9, 99, 999, …
  2. Find maximum number of 9, starting from the end and moving to the left.
  3. Change all found 9 in the end to 0 and previous digit increasy by 1.
  4. Handle border cases: if we have leading zero, remove it.

Complexity time complexity is O(n), where n is length of list. Additional space complexity is O(1), because we edit input data directly.

class Solution:
    def plusOne(self, digits):
        digits = [0] + digits
        
        end = len(digits) - 1
        while digits[end] == 9:
            end -= 1
    
        digits[end] += 1
        digits[end+1:] = [0] * (len(digits)-1-end)
                   
        return digits if digits[0] != 0 else digits[1:]      

If you like the solution, you can upvote it on leetcode discussion section: Problem 0066