Multiply Large Numbers as Strings
StringsAuto-graded · 22 test casesLast updated
Tests implementation of grade-school multiplication on arbitrarily large integers represented as strings without using built-in big integer operations.
Write a function that computes the product of two non-negative integers given as strings. You must not convert the strings to integers using built-in parsing or use any big integer libraries.
Your function should accept two string parameters, each representing a non-negative integer, and return their product as a string.
Constraints
- Each input string has length between 1 and 200
- Input strings contain only digits ('0'-'9')
- Input strings do not have leading zeros except for the number zero itself ("0")
- You may not use
int(),eval(), or any built-in arbitrary-precision arithmetic
Examples
Example 1
Input: multiply_strings('123', '456')
Output: '56088'
Example 2
Input: multiply_strings('2', '3')
Output: '6'
Example 3
Input: multiply_strings('0', '999')
Output: '0'
Example 4
Input: multiply_strings('99999999999999999999', '1')
Output: '99999999999999999999'
Hints
Hint 1
Consider how you would multiply two numbers by hand on paper, digit by digit, carrying as you go.
Hint 2
A product of an m-digit number and an n-digit number has at most m+n digits. You can allocate an array of that size to hold intermediate results.
Hint 3
When multiplying digit at position i in the first number by digit at position j in the second number, the contribution lands at a specific position in the result array. Think about which position that is.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution mimics the manual multiplication process taught in elementary school. When multiplying two numbers by hand, you multiply each digit of one number by each digit of the other, shift the partial products appropriately, and sum them up.
The key insight is that when you multiply the digit at index i in the first number by the digit at index j in the second number, this product contributes to position i + j + 1 in the final result array (when indexing from the left). Any overflow (carry) moves left to position i + j.
We allocate a result array of size m + n where m and n are the lengths of the input strings, since the product of an m-digit number and an n-digit number cannot exceed m + n digits.
The algorithm proceeds as follows:
- Handle the special case where either input is "0" by returning "0" immediately.
- Create a result array initialized to zeros with length equal to the sum of input lengths.
- Iterate through each digit of the first number from right to left (least significant to most significant).
- For each digit in the first number, iterate through each digit of the second number from right to left.
- Multiply the two digits, add any existing value at the target position and the current carry.
- Store the ones digit at the target position and propagate the tens digit as carry.
- After processing all digits of the second number for a given digit of the first number, add any remaining carry to the appropriate position.
- Remove leading zeros from the result (keeping at least one digit).
- Convert the digit array to a string and return.
Why It Works
This approach is correct because it faithfully replicates positional multiplication. Each digit pair contributes exactly once to the correct power of ten in the final sum. The carry mechanism ensures that no position holds a value greater than 9, maintaining proper digit representation.
The position formula i + j + 1 correctly maps each digit product to its place value. When multiplying num1[i] (which represents 10^(m-1-i)) by num2[j] (which represents 10^(n-1-j)), the product represents 10^(m-1-i + n-1-j), which corresponds to index i + j + 1 in an array of length m + n.
Complexity
- Time complexity: O(m × n), where m and n are the lengths of the input strings. We perform a constant amount of work for each pair of digits.
- Space complexity: O(m + n) for the result array.
For the maximum input size (200 digits each), this requires examining 40,000 digit pairs, which is efficient.
Solution Code
def multiply_strings(num1, num2):
if num1 == "0" or num2 == "0":
return "0"
result = [0] * (len(num1) + len(num2))
for i in range(len(num1) - 1, -1, -1):
digit1 = ord(num1[i]) - ord("0")
carry = 0
for j in range(len(num2) - 1, -1, -1):
digit2 = ord(num2[j]) - ord("0")
pos = i + j + 1
total = digit1 * digit2 + result[pos] + carry
result[pos] = total % 10
carry = total // 10
result[i] += carry
first = 0
while first < len(result) - 1 and result[first] == 0:
first += 1
return "".join(str(digit) for digit in result[first:])