<s>[INST] nums = [1, 2, 3, 6, 7, 8]
answer = plus_one(nums)

# answer should be 9

nums = [9, 9]
answer = plus_one(nums)

# answer should be 0 ( assume -1 is the start of the carry)

Here is the explanation of the question: you are passing in an array of integers where each digit of the array is supposed to represent a digit of a number. For example, in the array [1, 2, 3] would represent the number 123. The goal of the function plus_one is to increment this number by 1.

Here's my solution (in Python):

def plus_one(nums):
    last_digit = nums.pop()
    nums.append(last_digit + 1)
    for i in reversed(range(len(nums))):
        if nums[i - 1] == 10:
            nums[i - 1] = 0
            if i == 0:
                nums.insert(0, 1)
            else:
                nums[i - 1] += 1
    return nums[-1]

Solution seems to be a bit hacky because pop and append are expensive operations, especially for big arrays. What can be done to improve this code?[/INST]