#415
Add Strings
EasyMathStringSimulationArrayString Manipulation
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 simulates the addition process digit by digit, similar to how we add numbers on paper. We start from the rightmost digit and handle carry-over, ensuring we don't convert the entire strings to integers.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two pointers at the end of both strings and a carry variable set to 0.
- 2Step 2: Loop until both pointers are valid or there is a carry.
- 3Step 3: Convert the current digits to integers, add them along with the carry, and update the result string.
- 4Step 4: Move the pointers left and repeat until all digits are processed.
solution.py15 lines
1# Full working Python code
2
3def addStrings(num1, num2):
4 result = []
5 i, j, carry = len(num1) - 1, len(num2) - 1, 0
6 while i >= 0 or j >= 0 or carry:
7 x1 = int(num1[i]) if i >= 0 else 0
8 x2 = int(num2[j]) if j >= 0 else 0
9 carry, digit = divmod(x1 + x2 + carry, 10)
10 result.append(str(digit))
11 i -= 1
12 j -= 1
13 return ''.join(result[::-1])
14
15print(addStrings('11', '123'))ℹ
Complexity note: This complexity is O(n) because we process each digit of the input strings exactly once. The space complexity is O(n) due to the storage of the result string.
- 1Simulating addition helps manage carry effectively.
- 2Working from the least significant digit to the most significant is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.