KatInterview

43. Multiply Strings

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to multiply two large non-negative integers given as strings. We are explicitly forbidden from using built-in BigInteger libraries or converting the strings to integers directly. This suggests we need to simulate the process of long multiplication by hand, the method we learn in elementary school.

Solution

Multiply Strings in Python

class Solution:
    def multiply(self, num1: str, num2: str) -> str:
        # Handle edge case where one of the numbers is "0"
        if num1 == "0" or num2 == "0":
            return "0"
        
        m, n = len(num1), len(num2)
        # The maximum length of the product is m + n
        res = [0] * (m + n)
        
        # Multiply each digit of num1 with each digit of num2 from right to left
        for i in range(m - 1, -1, -1):
            for j in range(n - 1, -1, -1):
                # In Python, string digits can be directly converted to int
                d1 = int(num1[i])
                d2 = int(num2[j])
                product = d1 * d2
                
                # The product of num1[i] and num2[j] will be placed at indices i+j and i+j+1
                p1, p2 = i + j, i + j + 1
                
                # Add the product to the existing value at res[p2]
                total_sum = res[p2] + product
                
                # The units digit of sum goes to res[p2]
                res[p2] = total_sum % 10
                # The carry goes to res[p1]
                res[p1] += total_sum // 10
        
        # Find the first non-zero digit to skip leading zeros
        first_digit_idx = 0
        while first_digit_idx < len(res) and res[first_digit_idx] == 0:
            first_digit_idx += 1
            
        # Convert the list of digits to a string
        return "".join(map(str, res[first_digit_idx:]))

Multiply Strings in Java

class Solution {
    public String multiply(String num1, String num2) {
        // Handle edge case where one of the numbers is "0"
        if (num1.equals("0") || num2.equals("0")) {
            return "0";
        }

        int m = num1.length();
        int n = num2.length();
        // The maximum length of the product is m + n
        int[] res = new int[m + n];

        // Multiply each digit of num1 with each digit of num2 from right to left
        for (int i = m - 1; i >= 0; i--) {
            for (int j = n - 1; j >= 0; j--) {
                int d1 = num1.charAt(i) - '0';
                int d2 = num2.charAt(j) - '0';
                int product = d1 * d2;
                
                // The product of num1[i] and num2[j] will be placed at indices i+j and i+j+1
                int p1 = i + j;
                int p2 = i + j + 1;

                // Add the product to the existing value at res[p2]
                int sum = res[p2] + product;

                // The units digit of sum goes to res[p2]
                res[p2] = sum % 10;
                // The carry goes to res[p1]
                res[p1] += sum / 10;
            }
        }

        // Convert the result array to a string, skipping leading zeros
        StringBuilder sb = new StringBuilder();
        int i = 0;
        while (i < res.length && res[i] == 0) {
            i++;
        }
        
        // Append the remaining digits
        for (; i < res.length; i++) {
            sb.append(res[i]);
        }
        
        return sb.toString();
    }
}

Multiply Strings in C++

class Solution {
public:
    string multiply(string num1, string num2) {
        // Handle edge case where one of the numbers is "0"
        if (num1 == "0" || num2 == "0") {
            return "0";
        }
        
        int m = num1.length();
        int n = num2.length();
        // The maximum length of the product is m + n
        vector<int> res(m + n, 0);
        
        // Multiply each digit of num1 with each digit of num2
        for (int i = m - 1; i >= 0; i--) {
            for (int j = n - 1; j >= 0; j--) {
                int mul = (num1[i] - '0') * (num2[j] - '0');
                
                // The product of num1[i] and num2[j] will be placed at indices i+j and i+j+1
                int p1 = i + j, p2 = i + j + 1;
                
                // Add the product to the existing value at res[p2]
                int sum = mul + res[p2];
                
                // The units digit of sum goes to res[p2]
                res[p2] = sum % 10;
                // The carry goes to res[p1]
                res[p1] += sum / 10;
            }
        }
        
        // Convert the result vector to a string, skipping leading zeros
        string result_str = "";
        int i = 0;
        while (i < res.size() && res[i] == 0) {
            i++;
        }
        
        for (; i < res.size(); i++) {
            result_str += to_string(res[i]);
        }
        
        return result_str;
    }
};

Multiply Strings in TypeScript

function multiply(num1: string, num2: string): string {
    // Handle edge case where one of the numbers is "0"
    if (num1 === "0" || num2 === "0") {
        return "0";
    }

    const m = num1.length;
    const n = num2.length;
    // The maximum length of the product is m + n
    const res: number[] = new Array(m + n).fill(0);

    // Multiply each digit of num1 with each digit of num2 from right to left
    for (let i = m - 1; i >= 0; i--) {
        for (let j = n - 1; j >= 0; j--) {
            const d1 = parseInt(num1[i]);
            const d2 = parseInt(num2[j]);
            const product = d1 * d2;
            
            // The product of num1[i] and num2[j] will be placed at indices i+j and i+j+1
            const p1 = i + j;
            const p2 = i + j + 1;

            // Add the product to the existing value at res[p2]
            const sum = res[p2] + product;

            // The units digit of sum goes to res[p2]
            res[p2] = sum % 10;
            // The carry goes to res[p1]
            res[p1] += Math.floor(sum / 10);
        }
    }

    // Find the index of the first non-zero digit to handle leading zeros
    let firstDigitIndex = 0;
    while (firstDigitIndex < res.length && res[firstDigitIndex] === 0) {
        firstDigitIndex++;
    }

    // Slice from the first non-zero digit and join to form the result string
    return res.slice(firstDigitIndex).join('');
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.