SDE & MLE Prep

43. Multiply Strings

Problem

num1 and num2 are non-negative integers written as strings. Return their product as a string, without converting the whole inputs to integers or using big-integer libraries.

Example: "123" × "456" → "56088"

Constraints: lengths ≤ 200.

Digit i of a times digit j of b lands at positions i + j (carry) and i + j + 1. Accumulate into an array of length m + n, then strip leading zeros.

      1 2 3
    ×   4 5
   ---------
 pos: 0 1 2 3 4      3*5 -> pos[3,4], 2*5 -> pos[2,3], ...
 result 5 5 3 5      = 5535

Complexity: O(m·n).

class Solution:
    def multiply(self, num1: str, num2: str) -> str:
        m, n = len(num1), len(num2)
        pos = [0] * (m + n)
        for i in range(m - 1, -1, -1):
            for j in range(n - 1, -1, -1):
                s = int(num1[i]) * int(num2[j]) + pos[i + j + 1]
                pos[i + j + 1] = s % 10
                pos[i + j] += s // 10
        res = "".join(map(str, pos)).lstrip("0")
        return res or "0"