Multiply Strings
Medium
Topics
Given two non-negative integers num1 and num2 represented as strings, return the product, also as a string. Do not use any built-in big-integer library or convert the inputs directly to an integer.
Example 1
a
b
product
The key fact is positional:
a[i] * b[j] always lands in result positions i+j and i+j+1, so a buffer of n + m digits can accumulate every partial product with no shifting or intermediate strings. Leading zeros are stripped at the end. 2 × 3 = 6.The two operands and their product, one digit per cell.
Input: num1 = "2", num2 = "3" Output: "6"
Example 2
a
b
product
Input: num1 = "123", num2 = "456" Output: "56088"
Constraints
- 1 <= num1.length, num2.length <= 200
- The numbers contain only digits and have no leading zero (except "0").
Editorial — intuition, approach, complexity and pitfalls
Intuition
Grade-school multiplication: digit i of num1 times digit j of num2 contributes to position i + j (and a carry into i + j - 1) of the result, counting from the right.
Approach
- Allocate a result array of size
len1 + len2initialized to 0. - For each pair of digits, add the product into
pos[i+j+1], propagate carry topos[i+j]. - Skip leading zeros and join; if empty, the answer is "0".
Dry Run
"123" * "456". Grade-school multiplication on a digit buffer of length
len(s) + len(t) = 6. The product of s[i] and t[j] always lands at buffer position
i + j + 1, with its carry going to i + j.
s[2]=3 * t[2]=6 = 18 -> position 5 buffer 0 0 0 0 1 8
s[2]=3 * t[1]=5 = 15 -> position 4 buffer 0 0 0 1 6 8
s[2]=3 * t[0]=4 = 12 -> position 3 buffer 0 0 1 3 6 8
s[1]=2 * t[2]=6 = 12 -> position 4 buffer 0 0 1 4 8 8
s[1]=2 * t[1]=5 = 10 -> position 3 buffer 0 0 2 4 8 8
s[1]=2 * t[0]=4 = 8 -> position 2 buffer 0 1 0 4 8 8
s[0]=1 * t[2]=6 = 6 -> position 3 buffer 0 1 1 0 8 8
s[0]=1 * t[1]=5 = 5 -> position 2 buffer 0 1 6 0 8 8
s[0]=1 * t[0]=4 = 4 -> position 1 buffer 0 5 6 0 8 8
strip the leading zero -> "56088"
answer 56088
The i + j + 1 indexing is the only arithmetic to get right, and it is forced: two
digits at positions i and j from the left, in strings of length m and n, sit at
place values that multiply to a contribution m + n - i - j - 2 places from the
right -- which is buffer index i + j + 1 counting from the left.
No digit is ever allowed to exceed 9, because each write immediately reduces
modulo 10 and pushes the overflow one position left. The carry can only ever be a
single digit, so the loop needs no inner carry propagation.
Two guards bracket the result: "0" is returned up front when either factor is
zero, and leading zeros are stripped at the end -- the buffer is sized for the
worst case, so a shorter product always leaves one unused slot.Complexity
- Time — O(m*n): every digit pair is multiplied once.
- Space — O(m+n): the digit buffer for the product.
Common Pitfalls
- Handle the "0" case up front, and strip leading zeros from the final buffer.
Full Solution — all languages
class Solution:
def multiply(self, s, t):
if s == "0" or t == "0":
return "0"
res = [0] * (len(s) + len(t))
for i in range(len(s) - 1, -1, -1):
for j in range(len(t) - 1, -1, -1):
mul = (ord(s[i]) - 48) * (ord(t[j]) - 48)
total = mul + res[i + j + 1]
res[i + j + 1] = total % 10
res[i + j] += total // 10
out = []
for d in res:
if out or d != 0:
out.append(chr(48 + d))
return "".join(out) if out else "0"import java.util.*;
class Solution {
public String multiply(String s, String t) {
if (s.equals("0") || t.equals("0")) return "0";
int[] res = new int[s.length() + t.length()];
for (int i = s.length() - 1; i >= 0; i--) {
for (int j = t.length() - 1; j >= 0; j--) {
int mul = (s.charAt(i) - '0') * (t.charAt(j) - '0');
int total = mul + res[i + j + 1];
res[i + j + 1] = total % 10;
res[i + j] += total / 10;
}
}
StringBuilder out = new StringBuilder();
for (int d : res) {
if (out.length() > 0 || d != 0) out.append((char) ('0' + d));
}
return out.length() == 0 ? "0" : out.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string multiply(string s, string t) {
if(s=="0"||t=="0")return "0";
vector<int> res(s.size()+t.size(),0);
for(int i=s.size()-1;i>=0;i--)for(int j=t.size()-1;j>=0;j--) {
int mul=(s[i]-'0')*(t[j]-'0');
int sum=mul+res[i+j+1];
res[i+j+1]=sum%10;
res[i+j]+=sum/10;
}
string out;
for(int d:res) {
if(!(out.empty()&&d==0))out+=('0'+d);
}
return out.empty()?"0":out;
}
};/**
* @param {string} s
* @param {string} t
* @return {string}
*/ var multiply = function(s, t) {
if (s === "0" || t === "0") return "0";
const res = new Array(s.length + t.length).fill(0);
for (let i = s.length - 1; i >= 0; i--) {
for (let j = t.length - 1; j >= 0; j--) {
const mul = (s.charCodeAt(i) - 48) * (t.charCodeAt(j) - 48);
const total = mul + res[i + j + 1];
res[i + j + 1] = total % 10;
res[i + j] += Math.floor(total / 10);
}
}
let out = "";
for (const d of res) {
if (out.length > 0 || d !== 0) out += String.fromCharCode(48 + d);
}
return out.length === 0 ? "0" : out;
};