Multiply Strings
MediumNeetCode 150 Math & GeometryNielsenXTwo SigmaRokuProblem
Two non-negative whole numbers are given as strings, num1 and num2. Return their
product, also as a string.
The numbers can be hundreds of digits long, so you may not convert them to integers or use a big-number library. You have to multiply digit by digit, like long multiplication on paper.
Constraints
- 1 ≤ num1.length, num2.length ≤ 200
- num1 and num2 contain only the digits 0-9
- Neither number has a leading zero, except for the number 0 itself
Examples: pick one to animate
Solutions
TimeO(m · n)
SpaceO(m + n)
Time: Every digit of num1 is multiplied with every digit of num2 once.
Space: The result array has m + n slots.
The digit at index i of num1 times the digit at index j of num2 contributes to
slots i + j + 1 (ones) and i + j (carry) of a result array with m + n slots.
Add each product into its slot, push the carry one slot to the left, and strip any leading zero at the end.