Problem Statement in English
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Approach
We simulate the multiplication process as we do it manually. For each digit in the first number, we multiply it with each digit in the second number and store the result in an array.
And we’re done!
Solution in Python
class Solution:
def multiply(self, num1: str, num2: str) -> str:
if num1 == "0" or num2 == "0":
return "0"
n1, n2 = len(num1), len(num2)
result = [0] * (n1 + n2)
for i in reversed(range(n1)):
for j in reversed(range(n2)):
mul = (ord(num1[i]) - ord('0')) * (ord(num2[j]) - ord('0'))
tens, ones = i + j, i + j + 1
total = mul + result[ones]
result[ones] = total % 10
result[tens] += total // 10
prodstring = ""
for digit in result:
if not (prodstring == "" and digit == 0):
prodstring += str(digit)
return prodstring
Complexity
Time: $O(m \times n)$
Since we are multiplying each digit ofnum1with each digit ofnum2, wheremis the length ofnum1andnis the length ofnum2.Space: $O(m + n)$
Since we are storing the result in an array of sizem + n, wheremis the length ofnum1andnis the length ofnum2.
Mistakes I Made
I had to look this up :(
And we are done.