Add to Array-Form of Integer — LeetCode 989 Python Solution

EasyArrayMath
Problem
#989
Reading time
2 min

The problem

The array-form of an integer num is an array representing its digits in left to right order. For example, for num = 1321, the array form is [1,3,2,1].

Example

Input
num = [1,2,0,0], k = 34
Output
[1,2,3,4]
Explanation
1200 + 34 = 1234

Python solution

Python
class Solution:
    def addToArrayForm(self, num: List[int], k: int) -> List[int]:
        ans = []
        i = len(num) - 1
        while i >= 0 or k:
            k += 0 if i < 0 else num[i]
            k, x = divmod(k, 10)
            ans.append(x)
            i -= 1
        return ans[::-1]

Complexity

MeasureComplexity
TimeO(n), where n is the length of \textit{num}
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 989. Add to Array-Form of Integer is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 989. Add to Array-Form of Integer?
LeetCode 989. Add to Array-Form of Integer is rated Easy on LeetCode.
What is the time complexity of LeetCode 989. Add to Array-Form of Integer?
The Python solution on this page runs in O(n), where n is the length of \textit{num}.
What is the space complexity of LeetCode 989. Add to Array-Form of Integer?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 989. Add to Array-Form of Integer cover?
LeetCode 989. Add to Array-Form of Integer is tagged Array and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview