Two non-negative whole numbers come to you as strings of digits, num1 and num2. Return their product, also as a string of digits.
Work on the digits yourself: do not turn the whole strings into numbers, and do not use a big-number library. The numbers can have up to 200 digits, far beyond any built-in integer type.
Example 1
Input: num1 = "99", num2 = "99" Output: "9801" Why: 99 × 99 = 9801
2 more examples and the constraints
Example 2
Input: num1 = "7", num2 = "8" Output: "56" Why: one digit each, two digits out
Example 3
Input: num1 = "0", num2 = "5821" Output: "0" Why: anything times 0 is 0, written once
Constraints
- 1 ≤ length of num1, length of num2 ≤ 200
- Both strings contain only the digits 0 to 9
- Neither has a leading zero, unless it is exactly "0"
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Long multiplication, row by rowO(n·(m + n))
- One array of digit slotsO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for two 200-digit numbers | Verdict |
|---|---|---|---|
| Long multiplication, row by row | O(n·(m + n)) | Passes; many strings | |
| One array of digit slots | O(m·n) | Best; one array, no helpers |
m = digits in num1, n = digits in num2.
Edge cases to test
- A zero. "0" times "5821" must give "0", not "0000".
- Zeros inside. "100" times "100" is "10000"; zeros in the middle are real digits.
- Carry into a new digit. "7" times "8" is "56": the product is longer than both inputs.
- Longest inputs. Two 200-digit numbers give a 400-digit product; nothing may be turned into a built-in integer.
Common mistakes
- Converting the whole string to an integer, which overflows (and is not allowed).
- Forgetting to strip leading zeros, or stripping all of them so a zero product returns "".
- Writing the product into slot i + j instead of i + j + 1, which shifts every digit one place.
How to talk through it
- 1Clarify. Can either number be "0"? Are leading zeros possible? How long can the strings be?
- 2Start from school. Long multiplication works: one row per digit, then add. Say its cost.
- 3Find the slot rule. Digits i and j land at i + j + 1 with the carry at i + j, so one array is enough.
- 4Code it. Two loops from the right, then join and strip zeros, with "0" as the fallback.
- 5Test out loud. Run "0" times something, "100" times "100", and 99 × 99 for the carries.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?