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 1:
Input: num1 = "2", num2 = "3" Output: "6"
Example 2:
Input: num1 = "123", num2 = "456" Output: "56088"
Constraints:
1 <= num1.length, num2.length <= 200num1 and num2 consist of digits only.num1 and num2 do not contain any leading zero, except the number 0 itself.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:
Imagine you have two very large numbers written out on long strips of paper, and you need to find their product. The brute force approach relies on mimicking the manual multiplication method we learned in elementary school, exhaustively doing the heavy lifting by hand.
Here's how the algorithm would work step-by-step:
class Solution:
def multiply(self, num1: str, num2: str) -> str:
if num1 == "0" or num2 == "0":
return "0"
length_first = len(num1)
length_second = len(num2)
result_digits = [0] * (length_first + length_second)
# Process each digit from right to left to simulate manual column-by-column multiplication
for outer_index in range(length_first - 1, -1, -1):
for inner_index in range(length_second - 1, -1, -1):
digit_product = int(num1[outer_index]) * int(num2[inner_index])
position_low = outer_index + inner_index + 1
position_high = outer_index + inner_index
digit_product += result_digits[position_low]
result_digits[position_low] = digit_product % 10
result_digits[position_high] += digit_product // 10
# Convert the accumulated place-value digits into a string, skipping leading zeros
result_string = "".join(map(str, result_digits))
return result_string.lstrip("0")Instead of converting the large text representations into actual numbers, which would cause issues with extremely large values, the optimal approach mimics the traditional multiplication method you learned in elementary school. It systematically multiplies individual digits from right to left, tracks where each resulting product belongs based on its position, and accumulates the totals.
Here's how the algorithm would work step-by-step:
def multiply(num_string_one: str, num_string_two: str) -> str:
if num_string_one == "0" or num_string_two == "0":
return "0"
length_one = len(num_string_one)
length_two = len(num_string_two)
product_positions = [0] * (length_one + length_two)
# Multiplying each digit mimics manual long multiplication to prevent integer overflow.
for index_one in range(length_one - 1, -1, -1):
digit_one = int(num_string_one[index_one])
for index_two in range(length_two - 1, -1, -1):
digit_two = int(num_string_two[index_two])
product_sum = digit_one * digit_two + product_positions[index_one + index_two + 1]
product_positions[index_one + index_two + 1] = product_sum % 10
product_positions[index_one + index_two] += product_sum // 10
# Skipping leading zeros ensures the final string representation is properly formatted.
result_digits = []
for current_digit in product_positions:
if not (len(result_digits) == 0 and current_digit == 0):
result_digits.append(str(current_digit))
return "".join(result_digits)| Case | How to Handle |
|---|---|
| Multiplication by zero | If either input string is simply zero, the algorithm should immediately return zero to avoid redundant calculations. |
| Single-digit numbers | The nested loops will execute once and correctly compute the product of the two single characters. |
| Maximum-sized inputs up to four hundred digits each | Using an integer array of size equal to the sum of both string lengths prevents integer overflow and scales efficiently in O(N times M) time. |
| Inputs with leading zeros | The problem statement guarantees no leading zeros except for zero itself, but standard implementations still trim any accidental leading zeros from the final result string. |
| Negative numbers | The problem specifies non-negative integers, so sign parsing is not required and outputs are always positive. |
| Language-specific integer overflow | By treating input characters as strings and performing grade-school multiplication digit by digit into an integer array, we completely bypass standard integer type limits. |
| Results requiring carry propagation across multiple digits | The array-based accumulation step properly handles sums and carries by distributing values index by index from right to left. |
| Extremely skewed length inputs | The algorithm naturally adapts to different string lengths since the outer and inner loops iterate strictly over the dimensions of num1 and num2. |