#989
Add to Array-Form of Integer
EasyArrayMathArrayMath
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution directly simulates the addition process digit by digit, handling carries as we would in manual addition. This avoids the overhead of converting to and from integers, making it efficient.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an empty result array and a carry variable set to 0.
- 2Step 2: Start from the least significant digit (the end of the num array) and add each digit to k, along with any carry from the previous addition.
- 3Step 3: If the sum is 10 or more, calculate the new carry and store the digit in the result.
- 4Step 4: Continue until all digits in num and k are processed, including any remaining carry.
- 5Step 5: Reverse the result array to get the final answer in the correct order.
solution.py15 lines
1# Full working Python code
2num = [1, 2, 0, 0]
3k = 34
4result = []
5carry = k
6for digit in reversed(num):
7 total = digit + carry
8 result.append(total % 10)
9 carry = total // 10
10if carry > 0:
11 while carry > 0:
12 result.append(carry % 10)
13 carry //= 10
14result.reverse()
15print(result)ℹ
Complexity note: The time complexity is O(n) because we iterate through the digits of num once, and the space complexity is O(n) due to the result array storing the digits.
- 1Simulating addition digit by digit is more efficient than converting to integers.
- 2Handling carries is crucial in addition problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.