InterviewPrepKit

Home / Coding / Math & Geometry

Multiply Strings

medium Original ↗
Solving tips
  • Key insight: digit i (from the right) of num1 times digit j of num2 always lands in decimal place i+j, spilling carry into i+j+1.
  • Allocate an integer array of length m+n, accumulate every single-digit product, then resolve all carries in one right-to-left pass.
  • Short-circuit num1 == '0' or num2 == '0' to return '0', and strip leading zeros without wiping a genuine single '0'.
  • This is O(m*n) time and O(m+n) space; don't cheat with int() since the point is fixed-width-safe big-integer multiply.

Problem

You are given two non-negative integers, each represented as a string of decimal digits (num1 and num2). Return their product, also as a string.

The catch: you must do the arithmetic yourself. You may not convert the whole string to a native integer type (no int(num1), no big-integer library) — the exercise is to reproduce grade-school multiplication digit by digit. Neither input has a leading zero (except the literal "0"), and the answer must not have leading zeros either.

Examples

  • num1 = "2", num2 = "3""6" — a single-digit product.
  • num1 = "123", num2 = "456""56088" — the ordinary long-multiplication result.
  • num1 = "0", num2 = "52""0" — anything times zero is "0", with no leading zeros.

Constraints

  • 1 <= len(num1), len(num2) <= 200
  • Both strings contain only digits 09.
  • No leading zeros except the number "0" itself.
  • With up to 200 digits per number, the product can have ~400 digits — far beyond a 64-bit integer, which is exactly why you simulate the arithmetic.

Think about it first

Hint 1 Think about how you multiply on paper: multiply the top number by each digit of the bottom number, shift each partial product left, and add them all up. Every sub-step is single-digit multiplication plus carrying.
Hint 2 When digit `i` of one number (counting from the right) meets digit `j` of the other, their product lands in decimal place `i + j`. That observation lets you skip the "shift and add strings" bookkeeping entirely.
Hint 3 Allocate an integer array of length `len(num1) + len(num2)`. For every pair `(i, j)`, add `d1 * d2` into position `i + j + 1`, then do a single carry-propagation pass from right to left. Finally strip leading zeros and join.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.