↓Skip to main content
  1. LeetCode/

LeetCode 989: Add to Array-Form of Integer

·2 mins· ·
LeetCode Easy Array Math
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-26

  • Submissions: Runtime Error ×2 → Wrong Answer → Runtime Error → Accepted

Approach
#

A column-addition trick (Math Template 6): treat all of k as the carry. From the last element, k += num[i], the digit is k % 10, and k //= 10 carries on. If k remains after the array, prepend its digits.

My Attempts
#

As in LC 66, the first attempts converted to an integer, added k and split back: ''.join(num) on integers raised TypeError, then str(...).split() produced a single element: [0], 22 returned [22] instead of [2, 2]. Using list(str(...)) passed.

Solution
#

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

Complexity
#

Time O(max(n, log k)), space O(max(n, log k)).

Mistakes to Avoid
#

  • k may have more digits than the array; keep processing it after the array ends.
  • Return a list of digits, not one element from splitting a string.

Interview Explanation
#

I treat k as the carry, add from the last element, emit the ones digit and carry the rest, keep going while k remains, and reverse. Time O(max(n, log k)) without building a big integer.

Related

LeetCode 908: Smallest Range I
·1 min
LeetCode Easy Array Math
LeetCode 908 note: lower the maximum by k and raise the minimum by k; the answer is max(0, max - min - 2k)
LeetCode 914: X of a Kind in a Deck of Cards
·2 mins
LeetCode Easy Array Hash-Table Math Counting
LeetCode 914 note: every card count must be divisible by one X >= 2, i.e. the GCD of all counts is at least 2
LeetCode 892: Surface Area of 3D Shapes
·2 mins
LeetCode Easy Array Math Geometry Matrix
LeetCode 892 note: a stack of v cubes has 4v + 2 faces; subtract 2 × min for each overlap with the stacks above and to the left
LeetCode 883: Projection Area of 3D Shapes
·1 min
LeetCode Easy Array Math Geometry Matrix
LeetCode 883 note: the top view counts nonzero cells, and the front and side views sum each row’s and each column’s maximum
LeetCode 812: Largest Triangle Area
·2 mins
LeetCode Easy Array Math Geometry Polygons
LeetCode 812 note: with at most 50 points, enumerate every triple and take the largest shoelace area
LeetCode 628: Maximum Product of Three Numbers
·1 min
LeetCode Easy Array Math Sorting
LeetCode 628 note: after sorting there are only two candidates: the three largest, or the two smallest (negatives) times the largest