Multiply Strings — LeetCode 43 Python Solution

MediumMathStringSimulation
Problem
#43
Reading time
3 min

The problem

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

Example

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

Python solution

Python
class Solution:
    def multiply(self, num1: str, num2: str) -> str:
        if num1 == "0" or num2 == "0":
            return "0"
        m, n = len(num1), len(num2)
        arr = [0] * (m + n)
        for i in range(m - 1, -1, -1):
            a = int(num1[i])
            for j in range(n - 1, -1, -1):
                b = int(num2[j])
                arr[i + j + 1] += a * b
        for i in range(m + n - 1, 0, -1):
            arr[i - 1] += arr[i] // 10
            arr[i] %= 10
        i = 0 if arr[0] else 1
        return "".join(str(x) for x in arr[i:])

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m + n) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 43. Multiply Strings is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

On a study list

This problem is on NeetCode 150.

Frequently asked questions

How hard is LeetCode 43. Multiply Strings?
LeetCode 43. Multiply Strings is rated Medium on LeetCode.
What is the time complexity of LeetCode 43. Multiply Strings?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 43. Multiply Strings?
The Python solution on this page uses O(m + n) auxiliary space.
What topics does LeetCode 43. Multiply Strings cover?
LeetCode 43. Multiply Strings is tagged Math, String and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview