Multiply Strings

Schoolbook product into an int array — position i*j contributes to slots i+j and i+j+1; final carry-resolution sweep.

Medium
Time O(m * n) Space O(m + n)
LeetCode
4 min read
math string

Problem#

Multiply two non-negative big integers given as strings; return the product as a string. No BigInteger libraries.

Examples#

  • "2", "3""6".
  • "123", "456""56088".

Constraints#

  • 1 <= length <= 200.

Approach#

Result has at most m + n digits. For each (i, j), the product a[i] * b[j] contributes to positions i + j (tens) and i + j + 1 (units) of the result array. After accumulating, do a final carry-propagation sweep.

Solution#

Multiply Strings
class Solution {
public:
string multiply(string a, string b) {
if (a == "0" || b == "0") return "0";
int m = a.size(), n = b.size();
vector<int> r(m + n, 0);
for (int i = m - 1; i >= 0; --i)
for (int j = n - 1; j >= 0; --j) {
int p = (a[i] - '0') * (b[j] - '0');
int sum = p + r[i + j + 1];
r[i + j + 1] = sum % 10;
r[i + j] += sum / 10;
}
string out;
for (int d : r) {
if (!out.empty() || d != 0) out.push_back('0' + d);
}
return out;
}
};

Editorial#

The (i+j, i+j+1) trick is what makes this elegant — there’s no separate “shift by powers of 10” step. Each pair of multiplications correctly accumulates with carry handled in one pass. Skipping leading zeros at the end gives the canonical form.

Complexity#

  • Time: O(m * n).
  • Space: O(m + n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.