Multiply Strings (LeetCode 43): Solution and Explanation
Two non-negative integers arrive as decimal strings, possibly far longer than any built-in integer type. Return their product as a string, without converting the whole inputs to numbers or using a big-integer library.
Watch it run step by step
Try your own input and write the code →Intuition
You already know the algorithm from grade school: multiply the top number by each digit of the bottom number, shift each partial product, and add them up. Implementing it literally means building several intermediate strings and then adding strings together, which works but is fiddly.
The cleaner observation is about positions. If num1 has length m and num2 has length n, the product has at most m + n digits. When you multiply digit num1[i] by digit num2[j], that two-digit product lands in exactly two slots of the answer: its ones digit belongs at index i + j + 1 and its tens digit at index i + j. So you can allocate an array of m + n zeros and accumulate every pairwise product straight into it.
The only care needed is with carries. Process digits from right to left, add the new product to whatever already sits in slot i + j + 1, keep the ones digit there and push the tens into slot i + j. The left slot may temporarily exceed 9, but it is normalized later, when it becomes the right slot of some later pair. At the end, strip leading zeros.
Approach: Positional digit multiplication
- If either string is
"0", return"0"immediately. - Allocate
result = [0] * (m + n), enough room for any product of an m-digit and an n-digit number. - Loop
ifrom the last digit ofnum1down to 0, and inside itjfrom the last digit ofnum2down to 0. - Multiply the two digits and add the value already at
result[i + j + 1]to gettotal. - Store
total % 10inresult[i + j + 1]and addtotal // 10toresult[i + j]. - Join the digits into a string, strip leading zeros, and return it (or
"0"if nothing is left).
Step-by-step example
num1 = "123", num2 = "45"
m = 3,n = 2, soresult = [0,0,0,0,0].i = 2(digit 3): times 5 gives 15 at slots 3 and 4, soresult = [0,0,0,1,5]. Times 4 gives 12, plusresult[3] = 1is 13, soresult = [0,0,1,3,5].i = 1(digit 2): times 5 is 10, plusresult[3] = 3is 13, giving[0,0,2,3,5]. Times 4 is 8, plusresult[2] = 2is 10, giving[0,1,0,3,5].i = 0(digit 1): times 5 is 5, plusresult[2] = 0is 5, giving[0,1,5,3,5]. Times 4 is 4, plusresult[1] = 1is 5, giving[0,5,5,3,5].- Joining gives
"05535"; stripping the leading zero returns"5535", which is indeed 123 × 45.
Code: Python, Java, C++
1class Solution:
2 def multiply(self, num1: str, num2: str) -> str:
3 if num1 == "0" or num2 == "0":
4 return "0"
5
6 m, n = len(num1), len(num2)
7 result = [0] * (m + n)
8
9 for i in range(m - 1, -1, -1):
10 for j in range(n - 1, -1, -1):
11 mul = int(num1[i]) * int(num2[j])
12 p1, p2 = i + j, i + j + 1
13 total = mul + result[p2]
14
15 result[p2] = total % 10
16 result[p1] += total // 10
17
18 # Remove leading zeros
19 result_str = ''.join(map(str, result)).lstrip('0')
20 return result_str or "0"1class Solution {
2 public String multiply(String num1, String num2) {
3 if (num1.equals("0") || num2.equals("0")) return "0";
4
5 int m = num1.length(), n = num2.length();
6 int[] result = new int[m + n];
7
8 for (int i = m - 1; i >= 0; i--) {
9 for (int j = n - 1; j >= 0; j--) {
10 int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
11 int p1 = i + j, p2 = i + j + 1;
12 int total = mul + result[p2];
13
14 result[p2] = total % 10;
15 result[p1] += total / 10;
16 }
17 }
18
19 StringBuilder sb = new StringBuilder();
20 for (int digit : result) {
21 if (!(sb.length() == 0 && digit == 0)) {
22 sb.append(digit);
23 }
24 }
25 return sb.length() == 0 ? "0" : sb.toString();
26 }
27}1class Solution {
2public:
3 string multiply(string num1, string num2) {
4 if (num1 == "0" || num2 == "0") return "0";
5
6 int m = num1.size(), n = num2.size();
7 vector<int> result(m + n, 0);
8
9 for (int i = m - 1; i >= 0; i--) {
10 for (int j = n - 1; j >= 0; j--) {
11 int mul = (num1[i] - '0') * (num2[j] - '0');
12 int p1 = i + j, p2 = i + j + 1;
13 int total = mul + result[p2];
14
15 result[p2] = total % 10;
16 result[p1] += total / 10;
17 }
18 }
19
20 string str;
21 for (int digit : result) {
22 if (!(str.empty() && digit == 0)) {
23 str += to_string(digit);
24 }
25 }
26 return str.empty() ? "0" : str;
27 }
28};Time and space complexity
O(m × n)
Every digit of num1 is multiplied with every digit of num2 once, with constant work per pair, plus a linear pass to build the string.
O(m + n)
The result array has exactly m + n slots, and the output string has the same length.
Other approaches
Sum shifted partial products (time O(m × n), space O(m + n))
Multiply num1 by each digit of num2 to form a partial product string, append zeros for the shift, and add the strings with a string-addition helper. It mirrors pencil and paper but creates many temporary strings.
Karatsuba multiplication (time O(n^1.585), space O(n))
Split each number into halves and use three recursive multiplications instead of four. It beats the quadratic method only for very long inputs and is far more code than an interview needs.
Common mistakes
- Writing to
result[i + j]for the ones digit. The ones digit belongs ati + j + 1; usingi + jshifts everything by one place. - Overwriting
result[i + j]with the carry instead of adding to it. That slot may already hold a contribution from an earlier pair. - Forgetting the zero shortcut or the final fallback. Stripping zeros from an all-zero array leaves an empty string, which must become
"0". - Converting an entire input with
int(num1). That breaks the problem's rule and, in other languages, overflows for long inputs.
Frequently asked questions
Why does the product of an m-digit and n-digit number fit in m + n digits?
Each factor is less than a power of ten, 10^m and 10^n, so the product is less than 10^(m+n), which has at most m + n digits. The array therefore never needs to grow.
Why do the digits go to positions i + j and i + j + 1?
Counting from the right, digit i of num1 and digit j of num2 have place values that combine into one place in the product. Converting that back to an index from the left gives i + j + 1 for the ones digit and i + j for its carry.
What is the time complexity of multiply strings?
O(m × n), because each pair of digits is multiplied exactly once. Space is O(m + n) for the result array.
Can intermediate slots exceed 9?
Yes, the left slot result[i + j] can briefly hold a value above 9. It is normalized when a later pair treats it as its right slot, and slot 0 can never overflow because the product fits in m + n digits.