LeetSolved

Find solutions to all LeetCode problems here.

43.

Multiply Strings

Medium

Problem Description

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

Examples

Input: 2, 3
Output: 6

Input: 123, 456
Output: 56088

Constraints

Approach to Solve

Use the elementary multiplication algorithm with optimizations.

Code Implementation

class Solution:
    def multiply(self, num1: str, num2: str) -> str:
        if num1 == "0" or num2 == "0":
            return "0"
        m, n = len(num1), len(num2)
        result = [0] * (m + n)
        for i in range(m - 1, -1, -1):
            for j in range(n - 1, -1, -1):
                mul = (ord(num1[i]) - ord('0')) * (ord(num2[j]) - ord('0'))
                p1, p2 = i + j, i + j + 1
                total = mul + result[p2]
                result[p1] += total // 10
                result[p2] = total % 10
        res = ""
        for digit in result:
            if res or digit != 0:
                res += str(digit)
        return res if res else "0"

Explanation

This solution uses the elementary multiplication algorithm with optimizations. Here's a detailed explanation of the algorithm:

  1. Check if either num1 or num2 is "0". If so, return "0".
  2. Initialize a result array of size m + n (where m and n are the lengths of num1 and num2) to store intermediate results.
  3. Iterate through num1 and num2 from right to left, multiplying each pair of digits:
    • Calculate the product of the current digits.
    • Add this product to the appropriate positions in the result array.
    • Handle carry-over by updating the previous position.
  4. Convert the result array to a string, skipping leading zeros.
  5. Return the final string result.

The time complexity is O(m*n), where m and n are the lengths of num1 and num2. The space complexity is O(m+n) for the result array.

Complexity

  • Time Complexity: O(m*n)
  • Space Complexity: O(m+n)
Code copied to clipboard!