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. You must not use any built-in BigInteger library or convert the inputs to integer directly.
Key Insights
- Simulate the multiplication process similar to hand multiplication.
- Use an array to store intermediate results where the index correlation is based on the position of digits.
- Each multiplication may contribute a value that needs to be managed with a carry over in the result array.
- Handle the special case when either input is "0".
Space and Time Complexity
Time Complexity: O(n * m), where n and m are the lengths of num1 and num2 respectively.
Space Complexity: O(n + m), used for storing the intermediate multiplication results.
Solution
The solution multiplies each digit of num1 with each digit of num2 by simulating the grade-school multiplication algorithm. An array is used to store the intermediate sums at positions that correspond to the sum of the indices from num1 and num2. For two digits multiplied together, the product is added to the corresponding index in the result array, and any carry is added to the adjacent left cell. Finally, the array is converted back to a string while taking care to remove any leading zeros.
Data structures used:
- Array for intermediate multiplication results.
- Two nested loops to multiply each digit pair.
Algorithmic steps:
- Initialize an array of size (length of num1 + length of num2) with all zeros.
- Loop through digits of num1 and num2 in reverse order.
- Multiply the two digits, add the product to the corresponding position in the result array (taking into account any previous values).
- Manage the carry for each index.
- Convert the result array to a string, skipping any leading zeros.
- Return the final product string.