Skip to main content

46. Multiply Strings

mediumAsked at Ola

Multiply two non-negative integers represented as strings without using BigInt.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2 as a string. Do not convert the inputs directly to integers.

Constraints

  • 1 <= num1.length, num2.length <= 200
  • Both contain only digits
  • No leading zero except '0'

Examples

Example 1

Input
num1 = "2", num2 = "3"
Output
"6"

Example 2

Input
num1 = "123", num2 = "456"
Output
"56088"

Approaches

1. Convert to BigInt

Use BigInt to multiply.

Time
O(n*m)
Space
O(n+m)
return (BigInt(num1)*BigInt(num2)).toString();

Tradeoff:

2. Grade-school digit-by-digit

Multiply each digit pair into a position array of size n+m; carry once at the end.

Time
O(n*m)
Space
O(n+m)
function multiply(num1, num2) {
  if (num1 === '0' || num2 === '0') return '0';
  const out = Array(num1.length + num2.length).fill(0);
  for (let i = num1.length - 1; i >= 0; i--) {
    for (let j = num2.length - 1; j >= 0; j--) {
      const m = (num1.charCodeAt(i)-48) * (num2.charCodeAt(j)-48);
      const p1 = i + j, p2 = i + j + 1;
      const sum = m + out[p2];
      out[p2] = sum % 10;
      out[p1] += Math.floor(sum / 10);
    }
  }
  return out.join('').replace(/^0+/, '');
}

Tradeoff:

Ola-specific tips

Ola asks this without BigInt to test index bookkeeping; tie it to computing fare totals exactly when values exceed 64-bit precision in a daily payouts batch.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Multiply Strings and other Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →