989. Add to Array-Form of Integer - Explanation

Problem Link



1. Reverse and Add

class Solution:
    def addToArrayForm(self, num: List[int], k: int) -> List[int]:
        num.reverse()
        i = 0
        while k:
            digit = k % 10
            if i < len(num):
                num[i] += digit
            else:
                num.append(digit)
            carry = num[i] // 10
            num[i] %= 10
            k //= 10
            k += carry
            i += 1
        num.reverse()
        return num

Time & Space Complexity

  • Time complexity: O(max(n,m))O(max(n, m))
  • Space complexity: O(n)O(n).

Where nn is the size of the array numnum and mm is the number of digits in kk.


2. Without Reverse()

class Solution:
    def addToArrayForm(self, num: List[int], k: int) -> List[int]:
        from collections import deque
        result = deque()
        i = len(num) - 1
        carry = 0

        while i >= 0 or k > 0 or carry > 0:
            digit = k % 10
            sum_val = carry + (num[i] if i >= 0 else 0) + digit

            result.appendleft(sum_val % 10)
            carry = sum_val // 10

            k //= 10
            i -= 1

        return list(result)

Time & Space Complexity

  • Time complexity: O(max(n,m))O(max(n, m))
  • Space complexity: O(n)O(n)

Where nn is the size of the array numnum and mm is the number of digits in kk.