~/problems / Math & matrices

Multiply Strings

medium ~30 min

Two non-negative whole numbers arrive as strings of decimal digits, possibly hundreds of digits long. Write multiply_text(a, b) -> str that returns their product as a string of decimal digits.

  • Neither input has leading zeros, except that zero itself is "0". Your answer must follow the same rule.
  • Work digit by digit: don't turn a whole input into a built-in integer (or use a big-number library) and multiply that.
multiply_text("12", "34")       # "408"
multiply_text("999", "999")     # "998001"
multiply_text("0", "52")        # "0"
multiply_text("7", "8")         # "56"
  • 1 <= len(a), len(b) <= 1000.
  • Adding a to itself b times is hopeless at this size. Aim for O(len(a) · len(b)).
Show hint

when you multiply digit i of one number by digit j of the other, the product lands in a result position that depends only on i and j. Collect all those partial products first and deal with the carries at the end.

Topic: Math and matrices. Digit-by-digit arithmetic, matrix rotation and in-place tricks.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc