· By John Kavanagh

Multiply Strings in TypeScript: Put the Carries in Their Place

Rows of wooden beads on the metal rods of an old abacus.
Image by Alexandr Popadin, licensed from Unsplash.

Converting both strings to numbers and multiplying them is a wonderfully short solution to a different problem. Multiply Strings deliberately removes that shortcut, and sufficiently long inputs would lose integer precision through number anyway.

What remains is the multiplication we learned on paper: multiply digit pairs, put their contributions in the correct columns, and carry excess tens into the next column. The interesting coding decision is whether to carry immediately or keep the two operations separate.

I prefer a separate carry pass for this explanation. It gives the accumulation loop one job and makes the place‑value argument easier to inspect. The LeetCode problem accepts non‑negative decimal strings without leading zeroes, apart from zero itself, and disallows converting the whole inputs to integers or using a built‑in big‑integer implementation for the solution.


Reserve Enough Places for the Result

If the input lengths are m and n, their product needs at most m + n decimal digits. An m‑digit positive number is less than 10^m, and an n‑digit number is less than 10^n, so their product is less than 10^(m + n).

We'll allocate that many numeric buckets. They begin as zeroes, but during accumulation they are column totals rather than finished decimal digits. Calling them digits in the implementation is convenient; treating them as already normalised digits midway through the first pass would be a mistake.

For a digit at index i in the first string and index j in the second, their product contributes to bucket i + j + 1. The extra one accounts for the possible leading carry slot.

You can derive that index from powers of ten. The two digits represent powers m - 1 - i and n - 1 - j. Their product belongs at power m + n - 2 - i - j, which is index i + j + 1 in an array of length m + n.

That derivation is more useful than memorising the index expression. If the array direction changes, it tells us how to rebuild the formula instead of nudging offsets until an example passes.


Multiply First, Carry Second

Consider 27 × 34. We allocate four buckets. The pair products are 2 × 3 = 6, 2 × 4 = 8, 7 × 3 = 21, and 7 × 4 = 28.

Their place‑value contributions produce the raw buckets 0, 6, 29, 28. The two middle contributions share a column because they both represent tens in the expanded multiplication.

Now scan from right to left. The final bucket contains 28, so keep eight there and add two to its left neighbour. That neighbour becomes 31. Keep one there and carry three left, producing nine. The finished array is 0, 9, 1, 8, and removing the unused leading zero gives 918.

The right‑to‑left direction matters because a carry always moves towards a more significant position. When we finalise a bucket, all less significant buckets have already sent their carries into it. No later operation needs to change it again.

Keeping the two passes separate means every multiplication contributes exactly once before any normalisation begins. It also makes the intermediate table easy to compare with a hand calculation when an index is wrong.


Complete TypeScript Implementation

const multiply = (num1: string, num2: string): string => {
  if (num1 === '0' || num2 === '0') return '0';

  const digits: number[] = Array(num1.length + num2.length).fill(0);

  for (let left = 0; left < num1.length; left += 1) {
    for (let right = 0; right < num2.length; right += 1) {
      digits[left + right + 1] +=
        (num1.charCodeAt(left) - 48) * (num2.charCodeAt(right) - 48);
    }
  }

  for (let index = digits.length - 1; index > 0; index -= 1) {
    digits[index - 1] += Math.floor(digits[index] / 10);
    digits[index] %= 10;
  }

  const firstDigit = digits[0] === 0 ? 1 : 0;
  return digits.slice(firstDigit).join('');
};

Subtracting 48 from a decimal character's code gives its digit value. We convert individual digits, never the whole operand. This relies on the promised ASCII decimal digits; it isn't a parser for arbitrary Unicode numeral characters.

The early zero return also simplifies the final trimming. For non‑zero operands with lengths m and n, the product has either m + n - 1 or m + n digits. There can therefore be at most one unused leading slot. We don't need a loop stripping an unknown run of leading zeroes under the stated input format.

For a more general utility accepting padded inputs such as 00027, normalise them explicitly and revisit that trimming assumption. I wouldn't quietly claim that the interview function validates formats the problem already promises to supply correctly.


Why Ordinary Numbers are Safe Inside This Version

Avoiding whole‑number conversion doesn't mean we have to avoid numeric arithmetic altogether. Each digit product is at most 81. With input lengths at most 200, a raw column contains at most 200 such contributions, giving a maximum raw total of 16,200.

Carries increase later column totals slightly, but they remain tiny relative to JavaScript's exact integer range. For example, bounding an incoming carry by 1,800 keeps a processed column at most 18,000 and its outgoing carry at most 1,800. That is a conservative bound, sufficient to justify the representation.

The ECMAScript safe‑integer definition is relevant to that reasoning. The complete product may be hundreds of digits long, but no numeric bucket holds that complete product. The representation distributes its place values across small exact integers.

This is a useful general lesson in arithmetic algorithms: choose a representation whose intermediate values stay manageable, rather than only checking the final output type.


Complexity Without a Large‑Number Shortcut

Every digit in one input multiplies every digit in the other, giving O(m × n) time. The carry pass adds O(m + n) work, which doesn't change that overall bound for non‑empty inputs. The bucket array and constructed output use O(m + n) space.

Faster multiplication algorithms exist for much larger operands, but their extra machinery would obscure the point here. With at most 200 digits per input, the straightforward place‑value method is easy to verify and comfortably bounded.

My Add Two Numbers article also uses a digit representation with carries. Addition only combines corresponding positions; multiplication has to gather contributions from every relevant digit pair before each column is final.


Let the Tests Use a Stronger Calculator

The submitted solution must not use BigInt to multiply the inputs. An independent test oracle can. Keeping that distinction explicit lets us compare long products with exact arithmetic without smuggling the forbidden shortcut into the implementation.

I would test zero, one, single digits, powers of ten, mixed lengths, and long runs of nines. The nines exercise repeated carries; powers of ten exercise column placement without much carry noise. 27 × 34 = 918 is small enough to inspect every bucket by hand.

For broad small‑input coverage, compare every pair in a bounded integer range with their ordinary exact products. Then compare selected and deterministically generated strings up to the maximum length with BigInt results. Swapping operands must preserve the answer, and multiplying a non‑zero operand by ten should append one zero.

My Decode Ways walkthrough also depends on treating a string's digits according to the problem's rules. Here the values are positional contributions; there they form legal one‑ or two‑digit codes. In both cases, whole‑string conversion would erase information the algorithm needs.


Wrapping Up

The central decision is where each digit pair contributes. Once that index is justified, a separate right‑to‑left pass can normalise the columns without revisiting multiplication.

I find that separation easier to explain and test than carrying inside every pair update. It leaves us with two simple invariants: every pair has contributed once, then every finished column contains one decimal digit. No heroic integer conversion required.


Looking for technical direction?

I support teams that need senior judgement on React, Next.js, headless CMS architecture, performance, migrations, and technical SEO.