Taro Logo

Multiply Strings

#2 Most AskedMedium
0 views
Topics:
ArraysStrings

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 <= 200
  • num1 and num2 consist of digits only.
  • Both num1 and num2 do not contain any leading zero, except the number 0 itself.

Solution


Clarifying Questions

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:

  1. Are the input strings guaranteed to contain only numeric digits (0-9), and could either of them be represented as "0"?
  2. Are we allowed to use built-in BigInteger libraries or standard type conversions (like integer parsing), or should we implement the multiplication algorithm manually from scratch (e.g., grade-school multiplication)?
  3. What is the maximum possible length of the input strings num1 and num2?
  4. Can we assume the inputs will never contain leading zeros, except possibly for the number zero itself?
  5. Should the returned product string be formatted without any leading zeros?

Brute Force Solution

Approach

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:

  1. Take the first digit of the bottom number and multiply it by every single digit of the top number, one by one.
  2. Write down the result of each of those individual multiplications, making sure to keep track of any carried-over values just like you would on paper.
  3. Repeat this exact same process for the next digit of the bottom number, shifting your results over by one position to account for place value.
  4. Continue doing this until you have multiplied every single digit of the bottom number by every single digit of the top number.
  5. Collect all of the partial results you wrote down.
  6. Add all of those partial results together from start to finish to get your final combined number.
  7. Double-check your final sum to ensure all the place values align correctly and all carries were added properly.

Code Implementation

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")

Big(O) Analysis

Time Complexity
O(M * N) – Let M be the number of digits in the first string and N be the number of digits in the second string. The algorithm multiplies every digit of the first string by every digit of the second string using nested loops, resulting in M times N individual multiplications and additions. We then accumulate these partial products into a result array whose size is proportional to M plus N, adding a linear pass for the final summation. This leads to approximately M times N operations for the nested digit processing, which simplifies to O(M * N) or O(n squared) if the strings are of equal length n.
Space Complexity
O(M + N) – To store the intermediate partial products and the final combined number described in the manual multiplication steps, we allocate an auxiliary integer array of size M plus N, where M and N represent the lengths of the two input strings. A few primitive integer variables are also used to keep track of digit indices and carry values during the multiplication loops, but their memory footprint remains constant. As the lengths of the input strings increase, the size of this result array scales linearly with the combined number of digits. Therefore, simplifying this storage requirement yields a final auxiliary space complexity of O(M + N).

Optimal Solution

Approach

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:

  1. Think back to how you do long multiplication on paper by multiplying one digit of the bottom number with each digit of the top number, moving right to left.
  2. Prepare a dedicated space for holding the results, initially filled with zeros, making it large enough to hold the maximum possible final answer.
  3. Take the rightmost digit of the second number and multiply it by each digit of the first number, moving from right to left.
  4. Take the resulting products and place them into your holding space at the correct positions, making sure to align them based on whether they represent ones, tens, hundreds, and so on.
  5. Repeat the multiplication process for the next digit to the left of the second number, adding its products into the appropriate positions in the holding space along with any values carried over.
  6. Continue this process for every digit in the second number until all combinations have been multiplied and added together.
  7. Review your holding space from left to right, handling any numbers greater than nine by carrying the excess over to the next position just like standard addition.
  8. Finally, clean up any unnecessary leading zeros at the very front of your holding space to reveal the final answer.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(M * N) – Let M and N be the lengths of the two input strings. We iterate through every digit of the second string of length N, and for each of those digits, we iterate through every digit of the first string of length M to perform the multiplication. This nested digit-by-digit multiplication requires approximately M * N operations. Finally, cleaning up and converting the holding array takes linear time proportional to M + N, which simplifies to a final time complexity of O(M * N).
Space Complexity
O(N + M) – The auxiliary space is driven by a dedicated array of characters or digits used as a holding space to accumulate the intermediate products. Given two input strings of lengths N and M, this result array requires a maximum length of N plus M to securely store all potential digits of the final product. As the input sizes grow, this temporary storage scales linearly with the combined lengths of the inputs. Thus, the total extra memory simplifies to Big O of N plus M.

Edge Cases

Multiplication by zero
How to Handle:
If either input string is simply zero, the algorithm should immediately return zero to avoid redundant calculations.
Single-digit numbers
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
The problem specifies non-negative integers, so sign parsing is not required and outputs are always positive.
Language-specific integer overflow
How to Handle:
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
How to Handle:
The array-based accumulation step properly handles sums and carries by distributing values index by index from right to left.
Extremely skewed length inputs
How to Handle:
The algorithm naturally adapts to different string lengths since the outer and inner loops iterate strictly over the dimensions of num1 and num2.
0/4 completed