You are given two non-negative integers, num1
and num2
, represented as strings. Your task is to return the product of num1
and num2
, also represented as a string.
Important Constraints:
1 <= num1.length, num2.length <= 200
num1
and num2
consist of digits only.num1
and num2
do not contain any leading zero, except the number 0
itself.Examples:
num1 = "2", num2 = "3"
Output: "6"
num1 = "123", num2 = "456"
Output: "56088"
Explain your approach, analyze the time and space complexity, and provide the code for your solution. Consider edge cases such as when one or both numbers are zero.
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
We're given two numbers represented as strings, and we want to find their product, also as a string. The brute force approach mimics how you would do multiplication by hand on paper, multiplying each digit of one number with each digit of the other number and then handling the carries.
Here's how the algorithm would work step-by-step:
def multiply_strings_brute_force(first_number, second_number):
intermediate_results = []
for second_index in range(len(second_number) - 1, -1, -1):
carry = 0
current_result = []
second_digit = int(second_number[second_index])
for first_index in range(len(first_number) - 1, -1, -1):
first_digit = int(first_number[first_index])
product = first_digit * second_digit + carry
current_result.append(product % 10)
carry = product // 10
if carry:
current_result.append(carry)
current_result.reverse()
intermediate_results.append(current_result)
final_result = [0]
# Simulate addition with carry
for i, result in enumerate(intermediate_results):
shift = len(intermediate_results) - 1 - i
padded_result = result + [0] * shift
len_diff = len(final_result) - len(padded_result)
if len_diff < 0:
final_result = [0] * abs(len_diff) + final_result
elif len_diff > 0:
padded_result = [0] * len_diff + padded_result
carry = 0
temp_sum = []
for j in range(len(final_result) - 1, -1, -1):
digit_sum = final_result[j] + padded_result[j] + carry
temp_sum.append(digit_sum % 10)
carry = digit_sum // 10
if carry:
temp_sum.append(carry)
temp_sum.reverse()
final_result = temp_sum
# Remove leading zeros
while len(final_result) > 1 and final_result[0] == 0:
final_result.pop(0)
return ''.join(map(str, final_result))
The trick to multiplying large numbers represented as strings is to simulate how you'd do it by hand, but work with individual digits instead of the whole numbers. We'll multiply each digit of one number by each digit of the other, and then carefully add up the intermediate results, handling carries along the way.
Here's how the algorithm would work step-by-step:
def multiply_strings(number1, number2):
if number1 == "0" or number2 == "0":
return "0"
length_of_number1 = len(number1)
length_of_number2 = len(number2)
# This will store the intermediate products.
intermediate_products = [0] * (length_of_number1 + length_of_number2)
for i in range(length_of_number1 - 1, -1, -1):
for j in range(length_of_number2 - 1, -1, -1):
digit_number1 = int(number1[i])
digit_number2 = int(number2[j])
product = digit_number1 * digit_number2
# Determine positions in the result array.
position1 = i + j
position2 = i + j + 1
sum_at_position2 = intermediate_products[position2] + product
# Add the new product, propagating carry.
intermediate_products[position2] = sum_at_position2 % 10
intermediate_products[position1] += sum_at_position2 // 10
result = "".join(map(str, intermediate_products))
# Remove leading zeros from the result
start = 0
while start < len(result) - 1 and result[start] == '0':
start += 1
# Ensure no leading zeros
return result[start:]
Case | How to Handle |
---|---|
One or both input strings are null or empty | Return '0' if either input is null or empty as multiplying by zero results in zero. |
One or both input strings are '0' | Return '0' immediately if either input is '0' to avoid unnecessary calculations. |
Input strings contain leading zeros (e.g., '00123') | Trim leading zeros from the input strings before performing the multiplication to avoid incorrect results. |
Very large input strings that could lead to integer overflow | Use an array to store intermediate multiplication results, simulating manual multiplication, to handle large numbers. |
Input strings containing non-digit characters | Throw an exception or return an error message indicating invalid input if non-digit characters are encountered. |
Input strings represent negative numbers | Handle sign by checking the sign of both numbers, multiplying absolute values and applying correct sign to the final result. |
Maximum length input strings allowed by memory constraints | Ensure that the allocated memory for the result array is sufficient to hold the product of the two largest possible numbers. |
Both input strings are '1' | The algorithm should correctly return '1' as the product of 1 and 1 is 1 without errors. |