MediumNo. 0043

Multiply Strings — LeetCode 43 Python Solution

Topics
Math, String, Simulation
On a study list
NeetCode 150
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

PythonSolution
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

Time
O(m × n)
Space · auxiliary
O(m + n)

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

Related problems
No.ProblemDifficulty
0412Fizz BuzzEasy
0415Add StringsEasy
0537Complex Number MultiplicationMedium
0592Fraction Addition and SubtractionMedium
0640Solve the EquationMedium
1041Robot Bounded In CircleMedium

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 × 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.

Free to download. Check it runs on your machine, then pick a plan.