#43
Multiply Strings
MediumMathStringSimulationArrayString 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)
We can optimize the multiplication process by directly managing the carry and using a single result array to store intermediate results, which reduces the need for multiple passes.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a result array to hold the maximum possible digits of the product.
- 2Step 2: Loop through each digit of num2 from right to left.
- 3Step 3: For each digit in num2, loop through each digit of num1 from right to left, multiply them, and add the result to the appropriate position in the result array.
- 4Step 4: Handle carry for each multiplication and ensure to update the result array in place.
- 5Step 5: Convert the result array back to a string, skipping leading zeros.
solution.py12 lines
1# Full working Python code
2
3def multiply(num1: str, num2: str) -> str:
4 if num1 == '0' or num2 == '0': return '0'
5 result = [0] * (len(num1) + len(num2))
6 for i in range(len(num2) - 1, -1, -1):
7 for j in range(len(num1) - 1, -1, -1):
8 mul = (ord(num2[i]) - ord('0')) * (ord(num1[j]) - ord('0'))
9 sum_ = mul + result[i + j + 1]
10 result[i + j + 1] = sum_ % 10
11 result[i + j] += sum_ // 10
12 return ''.join(map(str, result)).lstrip('0')ℹ
Complexity note: The time complexity remains O(n²) due to the nested loops, but we efficiently manage the carries and results in a single pass. The space complexity is O(n) because we use an array to store the result.
- 1Understanding how to simulate multiplication manually helps in breaking down the problem.
- 2Managing carries properly is crucial for getting the correct result.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.