Bank app~25 min2s · 256 MBtarget O(n * m) time, O(n + m) spaceclassic twin: lc-43strings
A banking app keeps long-term ledger totals as text, because they do not fit any integer type. A growth report scales a total by a factor that is also kept as text. Both can have up to 1,000 digits.
The report may not turn the text into a number type, and it may not use a library for large numbers. Your team lead asks you to multiply the two by hand, digit by digit, as on paper.
Write multiply_digit_strings(first, second).
first and second are non-negative whole numbers written with the digits 0 to 9. Neither has a leading 0, unless the number is 0 itself.0, and "0" when the product is zero.Input: first = "123", second = "45"
Output: "5535"Give each place of the answer one cell, and use n + m cells for numbers of n and m digits. The digit of first at position i times the digit of second at position j belongs in cell i + j + 1. Add all such products into their cells, then carry from the right.
| Step | Cells (left to right) | Meaning |
|---|---|---|
| [1] | [0, 0, 0, 0, 0] |
five cells, all empty |
| [2] | [0, 4, 13, 22, 15] |
every pair of digits added into its cell |
| [3] | [0, 5, 5, 3, 5] |
carry from the right: 15 gives 5 and carry 1, 22 + 1 gives 3 and carry 2, and so on |
| [4] | 5535 |
the leading 0 is skipped |
Input: first = "0", second = "52"
Output: "0"Every product is zero. The answer is a single 0, not a row of zeros.
Input: first = "99", second = "99"
Output: "9801"The cells hold [0, 81, 162, 81] before carrying. Carrying from the right gives 9, 8, 0 and 9, with no leading 0.
1 ≤ length of first ≤ 1000 and 1 ≤ length of second ≤ 10000 to 90, unless the number is 0 itselfNumbers of 1,000 digits do not fit any integer type, so every step happens on digits. Multiplying each pair of digits costs 1,000 × 1,000 = 1,000,000 steps, and that is fine.
Repeated addition is not. Adding the first number up to 9 times for each of 1,000 digits is about 9,000 additions. Each one handles 1,000 digits, and building a sum by inserting digits in front is slower again.