PracticeNeetCode ↗LeetCode ↗
Given two non-negative integers num1 and num2 represented as strings, return their product, also as a string — without converting either input directly to an integer.
i of num1 times digit j of num2 contributes to result positions i+j and i+j+1 — that index mapping is the key trick."0", return "0" immediately.len(num1) + len(num2).(i, j), multiply them and add the product into result[i+j+1], carrying the overflow into result[i+j].result, carrying any digit ≥ 10 into the position to its left.Time: O(m · n) — Space: O(m + n)
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)
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
mul = int(num1[i]) * int(num2[j])
p1, p2 = i + j, i + j + 1
total = mul + result[p2]
result[p2] = total % 10
result[p1] += total // 10
result_str = "".join(map(str, result)).lstrip("0")
return result_str if result_str else "0"How the solution above works, piece by piece.
result has m + n slots, enough for any product.num1[i] × num2[j] belongs at positions i + j and i + j + 1.p2, keep the units digit there, and push the carry into p1.Running it on num1 = "123", num2 = "456":