989. Add to Array-Form of Integer - Explanation
Description
The array num contains the decimal digits of a non-negative integer, from most significant to least significant. It has no leading zero unless the entire number is zero. Add the positive integer k and return the sum as an array of decimal digits in the same order. The input number may have thousands of digits.
Example 1:
Input: num = [9,9]
k = 1
Output: [1,0,0]Explanation: The digits represent 99. Adding 1 gives 100, so the returned digits are [1,0,0].
Example 2:
Input: num = [0]
k = 37
Output: [3,7]Explanation: The input represents zero. Adding 37 gives the digits [3,7].
Example 3:
Input: num = [1,0,0]
k = 25
Output: [1,2,5]Explanation: The input represents 100. Adding 25 gives 125, represented by [1,2,5].
Constraints:
1 <= num.length <= 100000 <= num[i] <= 9numhas no leading zeros unless it is[0].1 <= k <= 10000
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- Arrays - Traversing and modifying arrays, especially from the end
- Basic Math Operations - Understanding modulo (%) and integer division (/) for digit extraction
- Carry Propagation - How carry works when adding numbers digit by digit
1. Reverse and Add
Intuition
Adding two numbers digit by digit is straightforward when we start from the least significant digit. Since the array represents a number with the most significant digit first, we can either reverse the array or process it from the end.
The trick here is to treat k as a running sum that absorbs both the addition and the carry. At each step, we add the current digit to k, extract the last digit of k as our result digit, and divide k by 10 to prepare for the next iteration. This elegantly combines the carry propagation into a single variable.
Algorithm
- Process the array from right to left (or reverse it first).
- For each position
i:- Add
num[i]tok. - The result digit at this position is
k % 10. - Update
k = k / 10to carry over any excess.
- Add
- After processing all digits, if
k > 0, continue extracting digits fromk. - Reverse the result (if built in reverse order) and return.
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 numTime & Space Complexity
- Time complexity:
- Space complexity: .
Where is the size of the array and is the number of digits in .
2. Without Reverse()
Intuition
We can avoid the explicit reverse operation by inserting digits at the front of our result as we compute them. Using a deque (double-ended queue) or linked list allows O(1) insertion at the front.
The logic remains the same: process from right to left, compute each digit with the carry, and build the result. The difference is just in how we construct the output to avoid a final reversal step.
Algorithm
- Initialize a deque or linked list for the result, and set
carry = 0. - Start from the last index of
numand the last digit ofk. - While there are digits remaining in
num, digits remaining ink, orcarry > 0:- Compute
sum = carry + num[i] (if valid) + k % 10. - Insert
sum % 10at the front of the result. - Update
carry = sum / 10. - Move to the next digit: decrement
iand dividekby10.
- Compute
- Return the result as a list.
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:
- Space complexity:
Where is the size of the array and is the number of digits in .
Common Pitfalls
Forgetting the Final Carry
After processing all digits of the array and k, there may still be a remaining carry. Forgetting to handle this results in incorrect answers for cases like [9,9,9] + 1 = [1,0,0,0].
# Wrong: stopping when array and k are exhausted
while i >= 0 or k > 0: # Missing: or carry > 0
# ...Processing Digits in Wrong Order
The array stores the most significant digit first, but addition needs to start from the least significant digit. Forgetting to process from right to left (or reverse the array) produces wrong results.
# Wrong: processing from left to right
for i in range(len(num)): # Should be range(len(num)-1, -1, -1)
k += num[i]
Sign in to join the discussion