Multiply Strings

Medium
39.

Multiply Strings

Multiply Strings is a medium coding problem on strings, math and simulation, asked in Twitter and Two Sigma interviews.

Given two non-negative integers num1 and num2 represented as strings, return their product as a string.

You must not use built-in big-integer types or convert the inputs directly to integers.

Example 1

Input
num1 = "2", num2 = "3"
Output
"6"

Example 2

Input
num1 = "123", num2 = "456"
Output
"56088"

Constraints

  • 1 <= num1.length, num2.length <= 15
  • Digits only, no leading zeros (except the number 0 itself).
Write your solution here. Running it against the tests needs a free account — what you type comes with you.Sign in to run
/**
 * @param {string} num1
 * @param {string} num2
 * @return {string}
 */
var multiply = function(num1, num2) {
    // Write your code here
    
};

Sign in to run your own test cases

Sign in

Multiply Strings — Solution in Python, Java & C++

Multiply Strings solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. A medium problem on strings and math.

Multiply Strings is a medium coding problem on strings, math and simulation, asked in Twitter and Two Sigma interviews.

  • Difficulty: Medium
  • Topics: Strings, Math, Simulation
  • Asked at: Twitter, Two Sigma
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

Given two non-negative integers num1 and num2 represented as strings, return their product as a string.

You must not use built-in big-integer types or convert the inputs directly to integers.

Example 1

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2

Input: num1 = "123", num2 = "456"
Output: "56088"

Constraints

  • 1 <= num1.length, num2.length <= 15
  • Digits only, no leading zeros (except the number 0 itself).

Hints for Multiply Strings

  1. Hint 1

    Grade-school multiplication: digit i × digit j contributes to positions i + j and i + j + 1.

  2. Hint 2

    Work in a digit array, then trim the leading zeros.

How to solve Multiply Strings

Do long multiplication the way it is taught by hand, but into a digit array rather than a number. The key observation is positional: the product of num1[i] and num2[j] always lands in positions i + j and i + j + 1 of the result, counting from the left of an array of length n1 + n2.

Approach

  1. Return "0" immediately if either input is "0".
  2. Allocate a digit array of length n1 + n2, all zeros.
  3. For each pair of digits, multiply them and add the product into position i + j + 1, carrying the overflow into position i + j.
  4. Work from the least significant digits so carries propagate correctly.
  5. Skip leading zeros and turn the remaining digits into a string.

Why it works

The positional rule follows from place value: digit i of a length-n1 number has weight 10^(n1-1-i), so multiplying two digits gives weight 10^(n1+n2-2-i-j) — which is exactly the slot i + j + 1 in a left-aligned array of length n1 + n2. Since each partial product is at most 81, adding it to an existing digit can carry at most one place, which is why two positions per pair suffice and no wide arithmetic is ever needed.

Complexity

  • Time — O(n1 · n2)
  • Space — O(n1 + n2)

Pitfalls

  • The zero case must be handled up front, or the result comes out as a string of zeros.
  • The array needs n1 + n2 slots — the product can be that long.
  • Add into the existing digit before splitting the carry, or accumulated carries are lost.
  • Trim leading zeros at the end, but never trim the result down to an empty string.

Reference solution

Python

def multiply(num1: str, num2: str) -> str:
    if num1 == "0" or num2 == "0":
        return "0"
    n1, n2 = len(num1), len(num2)
    digits = [0] * (n1 + n2)
    for i in range(n1 - 1, -1, -1):
        for j in range(n2 - 1, -1, -1):
            total = int(num1[i]) * int(num2[j]) + digits[i + j + 1]
            digits[i + j + 1] = total % 10
            digits[i + j] += total // 10
    out = "".join(map(str, digits)).lstrip("0")
    return out or "0"

Java

public static String multiply(String num1, String num2) {
    if (num1.equals("0") || num2.equals("0")) return "0";
    int n1 = num1.length(), n2 = num2.length();
    int[] digits = new int[n1 + n2];
    for (int i = n1 - 1; i >= 0; i--) {
        for (int j = n2 - 1; j >= 0; j--) {
            int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
            int total = mul + digits[i + j + 1];
            digits[i + j + 1] = total % 10;
            digits[i + j] += total / 10;
        }
    }
    int start = 0;
    while (start < digits.length - 1 && digits[start] == 0) start++;
    StringBuilder out = new StringBuilder();
    for (int i = start; i < digits.length; i++) out.append((char) ('0' + digits[i]));
    return out.toString();
}

C++

string multiply(string num1, string num2) {
    if (num1 == "0" || num2 == "0") return "0";
    int n1 = (int) num1.size(), n2 = (int) num2.size();
    vector<int> digits(n1 + n2, 0);
    for (int i = n1 - 1; i >= 0; i--) {
        for (int j = n2 - 1; j >= 0; j--) {
            int mul = (num1[i] - '0') * (num2[j] - '0');
            int total = mul + digits[i + j + 1];
            digits[i + j + 1] = total % 10;
            digits[i + j] += total / 10;
        }
    }
    int start = 0;
    while (start < (int) digits.size() - 1 && digits[start] == 0) start++;
    string out;
    for (int i = start; i < (int) digits.size(); i++) out += (char) ('0' + digits[i]);
    return out;
}

JavaScript

var multiply = function(num1, num2) {
    if (num1 === "0" || num2 === "0") return "0";
    const n1 = num1.length, n2 = num2.length;
    const digits = new Array(n1 + n2).fill(0);
    for (let i = n1 - 1; i >= 0; i--) {
        for (let j = n2 - 1; j >= 0; j--) {
            const total = (num1.charCodeAt(i) - 48) * (num2.charCodeAt(j) - 48) + digits[i + j + 1];
            digits[i + j + 1] = total % 10;
            digits[i + j] += Math.floor(total / 10);
        }
    }
    let out = digits.join("").replace(/^0+/, "");
    return out === "" ? "0" : out;
};

Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 515 strings problems · the whole catalogue

Learn the technique: Strings