Multiply two numbers represented by linked lists

Easy

Problem

Two numbers are stored as linked lists, most significant digit first. Return their product, usually modulo 1e9 + 7 because the numbers can be huge.

Example 1

Input:  3 → 2 and 2
Output: 64

Also asked as: Multiply 2 no. represented by LL

Test cases

Case 1

Input:    [3,2], [2]
Expected: 64

Case 2

Input:    [9,9,9], [9,9,9]
Expected: 998001

Case 3

Input:    [1,0,0], [1,0]
Expected: 1000

Case 4

Input:    [0], [9,9]
Expected: 0

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Build each number, multiply, mod for overflow safety

Time O(n + m)Space O(1)

Fold each list into an integer (num = num*10 + digit), multiply. Use modulo 1e9+7 if the problem wants that.

function multiplyLists(a, b) {
const MOD = 1_000_000_007n;
const toNum = (h) => { let n = 0n; for (; h; h = h.next) n = (n * 10n + BigInt(h.val)) % MOD; return n; };
return Number((toNum(a) * toNum(b)) % MOD);
}