Multiply Strings (LeetCode 43): Solution and Explanation

Medium
Math
String
Simulation

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. If either string is "0", return "0" immediately.
  2. Allocate result = [0] * (m + n), enough room for any product of an m-digit and an n-digit number.
  3. Loop i from the last digit of num1 down to 0, and inside it j from the last digit of num2 down to 0.
  4. Multiply the two digits and add the value already at result[i + j + 1] to get total.
  5. Store total % 10 in result[i + j + 1] and add total // 10 to result[i + j].
  6. 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"
  1. m = 3, n = 2, so result = [0,0,0,0,0].
  2. i = 2 (digit 3): times 5 gives 15 at slots 3 and 4, so result = [0,0,0,1,5]. Times 4 gives 12, plus result[3] = 1 is 13, so result = [0,0,1,3,5].
  3. i = 1 (digit 2): times 5 is 10, plus result[3] = 3 is 13, giving [0,0,2,3,5]. Times 4 is 8, plus result[2] = 2 is 10, giving [0,1,0,3,5].
  4. i = 0 (digit 1): times 5 is 5, plus result[2] = 0 is 5, giving [0,1,5,3,5]. Times 4 is 4, plus result[1] = 1 is 5, giving [0,5,5,3,5].
  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"

Time and space complexity

Time

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.

Space

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 at i + j + 1; using i + j shifts 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.