Multiply Strings
Problem
Given two non-negative integers
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Examples
Example 1
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2
Input: num1 = "123", num2 = "456"
Output: "56088"
Key Insight
Product of digits at positions i and j contributes to position i+j and i+j+1.
Like manual multiplication: num1[i] × num2[j] goes to result[i+j] and result[i+j+1]. Handle carries, remove leading zeros.
How to Approach This Problem
Pattern Recognition: When you see keywords like
multiply strings math-and-geometry,
think Math & Geometry.
Step-by-Step Reasoning
1
Product of m-digit and n-digit numbers has at most:
Answer: m + n digits
Maximum is when 999...9 × 999...9 which has m+n digits.
2
num1[i] * num2[j] contributes to positions:
Answer: i + j and i + j + 1
Digit at position i has value × 10^(n1-1-i). Product at positions i+j, i+j+1 in result.
3
We process digits:
Answer: Right to left for both
Rightmost digits are ones place. Process like manual multiplication.
4
After accumulating at result[i+j+1]:
Answer: Either works
Can accumulate all products first, then handle carries. Or propagate immediately.
5
Leading zeros in result:
Answer: Should be removed
"00123" should become "123". Handle edge case of "0".
Solution
def multiply(num1: str, num2: str) -> str:
if num1 == "0" or num2 == "0":
return "0"
m, n = len(num1), len(num2)
result = [0] * (m + n)
# Multiply each digit pair
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
prod = int(num1[i]) * int(num2[j])
p1, p2 = i + j, i + j + 1
total = prod + result[p2]
result[p2] = total % 10
result[p1] += total // 10
# Convert to string, skip leading zeros
result_str = ''.join(map(str, result)).lstrip('0')
return result_str if result_str else "0"
Complexity Analysis
| Time | O(m × n) |
|---|---|
| Space | O(m + n) |
Master This Pattern
Build intuition with interactive MCQs. Practice Math & Geometry problems in the LeetEye app.
Download LeetEye Free