Add to Array-Form of Integer - Problem
In computer science, we often need to work with numbers in different representations. The array-form of an integer is one such representation where each digit of the number becomes an element in an array, ordered from left to right.
For example:
Your task is to implement addition in this array format. Given an array
The challenge lies in handling carries properly, just like when you add numbers by hand!
For example:
- The number
1321becomes[1, 3, 2, 1] - The number
999becomes[9, 9, 9]
Your task is to implement addition in this array format. Given an array
num representing a number and an integer k, you need to compute num + k and return the result in array-form.The challenge lies in handling carries properly, just like when you add numbers by hand!
Input & Output
example_1.py โ Basic Addition
$
Input:
num = [1,2,0,0], k = 34
โบ
Output:
[1,2,3,4]
๐ก Note:
The array [1,2,0,0] represents 1200, and 1200 + 34 = 1234, which in array form is [1,2,3,4]
example_2.py โ Carry Propagation
$
Input:
num = [2,7,4], k = 181
โบ
Output:
[4,5,5]
๐ก Note:
274 + 181 = 455. Notice how the addition creates carries that propagate through multiple digits
example_3.py โ Result Longer Than Input
$
Input:
num = [9,9,9], k = 1
โบ
Output:
[1,0,0,0]
๐ก Note:
999 + 1 = 1000. The result has more digits than the original array due to carry overflow
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Set pointer to rightmost digit, k becomes our initial carry
2
Add Current
Add carry to current digit (or 0 if past array start)
3
Extract & Carry
Take remainder as result digit, quotient as new carry
4
Move Left
Continue until no more digits and no carry remains
5
Reverse
Since we built the result backwards, reverse it
Key Takeaway
๐ฏ Key Insight: By treating k as an initial carry and processing from right to left, we naturally handle all carries without needing to convert to integers, making this approach both elegant and overflow-safe.
Time & Space Complexity
Time Complexity
O(max(n, log k))
We process each digit of the input array once, plus additional digits from k if k is larger than the array represents
โก Linearithmic
Space Complexity
O(max(n, log k))
Space for the result array, which can be at most one digit longer than the larger of the two inputs
โก Linearithmic Space
Constraints
- 1 โค num.length โค 104
- 0 โค num[i] โค 9
- num does not contain any leading zeros except for the zero itself
- 1 โค k โค 104
- No leading zeros in the result array
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code