Problem 989

Abstract / Summary

Add a number to a list that represents another number in array form and return the resulting array form.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0989.py

class Solution:
    def addToArrayForm(self, num: List[int], k: int) -> List[int]:
        sys.set_int_max_str_digits(0) # unlimited
        x  = int("".join([ str(n) for n in num ]))
        return [ int(c) for c in str(x + k) ]
5 lines | 235 bytes | submitted October 27, 2023 | GitHub   20% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 45% (500k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a single method addToArrayForm that receives a list of decimal digits representing a non-negative integer (num) and an integer k. The goal is to return the sum of the two numbers, expressed again as a list of decimal digits. The solution follows a straightforward conversion strategy: it transforms the digit list into a string, parses it as an integer, adds k, and finally converts the result back into a list of digits.

Key Steps

Removing the Python integer-to-string digit limit

sys.set_int_max_str_digits(0)  # unlimited

By invoking sys.set_int_max_str_digits with a zero argument, the code disables the safety limit introduced in recent Python versions that restricts the number of digits allowed when converting very large integers to or from strings. This call ensures that the subsequent conversion of potentially huge numbers will not raise a ValueError, allowing the algorithm to handle inputs whose length exceeds the default threshold.

Building the integer from the digit array

x = int("".join([str(n) for n in num]))

The list comprehension iterates over each element n in num, casts it to a string, and the join operation concatenates those characters into a single numeric string. The outer int call then parses this string into a native Python integer. This step effectively reconstructs the original number encoded by the digit array.

Adding the second operand

x + k

At this point x holds the integer value of num. Adding k uses Python’s arbitrary-precision integer arithmetic, guaranteeing an exact result regardless of the magnitude of the operands.

Converting the sum back to a digit list

[ int(c) for c in str(x + k) ]

The sum is first turned into a string with str, producing a sequence of character digits. A list comprehension then iterates over each character c, converts it back to an integer, and collects the results into a new list. This list constitutes the final answer in the required array-form representation.

Edge Cases Handled

The code gracefully manages inputs where the digit list represents a number with many digits, potentially exceeding the default conversion limit. By disabling the digit limit, it avoids runtime errors for extremely large inputs. The conversion process also tolerates leading zeros in the input list because the string concatenation will include those zeros, and the subsequent integer conversion will naturally discard them, yielding the mathematically correct value. When k is zero, the addition step leaves the integer unchanged, and the final conversion reproduces the original digit sequence (minus any leading zeros that were stripped by the integer conversion). If num is an empty list, the join operation yields an empty string; converting an empty string to an integer would raise an exception, but typical problem constraints guarantee at least one digit, so the code operates under that assumption.

Performance Optimizations Observed

The implementation leverages Python’s built-in string and integer handling, which are highly optimized in C. The use of a single join call to assemble the numeric string avoids repeated string concatenation, reducing overhead. Converting the entire number to an integer in one step enables the addition to be performed using the language’s native arbitrary-precision arithmetic, which is faster than manually simulating digit-wise addition in Python loops. Finally, the list comprehension that extracts digits from the result string runs in a tight C-level loop, providing efficient element-wise conversion without explicit Python-level iteration constructs. These choices collectively minimize the amount of Python-level code executed and rely on the interpreter’s optimized core operations.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a line of numbered blocks scattered on the floor. Each block has a single digit painted on it. To make sense of the collection, the computer gathers all those blocks and sticks them together to form one big, giant number. Once the computer has that big number, it invites another number called k to join the party. The computer adds the two of them together to find a brand new, even bigger total. After the adding is finished, the computer breaks the new total back apart into individual digits again. It lays these new digits out in a neat row, just like the original set of blocks used at the very beginning.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 4 | μ = 4.11 | σ = 1.50

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
varunu28 Java
vthwang Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
varunu28 Java
vthwang Java
YuriSpiridonov Python
38 links | 24 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 similar problems

Solved On The Same Day

2 easy 2 medium
5 solutions   October 27, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality