Skip to problem
←

Multiply Numbers Stored in Linked Lists

Easy 0 attempts

You're given two numbers, each represented as a linked list where every node holds a single digit. Digits are stored most significant first. Return their product modulo 10^9 + 7 as an integer.

The lists represent nonnegative base-10 integers and may contain leading zeros. For example, [0,0,3] represents 3, and [3,2] represents 32. Return only the remainder, which lies from 0 through 1000000006. Do not convert the full represented numbers to JavaScript Number: they may contain up to 100 digits.

Function contract

Implement multiplyLists(l1, l2). The editor converts each digit array into a nonempty linked list with val and next properties. Digits run from most significant to least significant.

Output: Return (first number × second number) modulo 1000000007 as a JavaScript number, not a linked list or BigInt.

Example 1

Input
l1 = [3,2]
l2 = [2]
Output
64

Example 2

Input
l1 = [0]
l2 = [9,9]
Output
0
Constraints
  • 1 to 100 nodes per list
  • 0 <= Node.val <= 9

Accumulate Digits Modulo 10^9 + 7

Read each digit from left to right using remainder = (remainder × 10 + digit) mod M, where M = 1000000007. Reducing after every digit keeps the accumulated values bounded even for 100-digit inputs.

Use BigInt for exact arithmetic: multiplying two reduced remainders can still exceed Number.MAX_SAFE_INTEGER. Reduce their product before converting the final result to Number; that remainder is safely below M. Leading zeros naturally leave the accumulator unchanged.

javascript
function multiplyLists(l1, l2) {
  let n1 = 0n, n2 = 0n;
  while (l1) { n1 = (n1 * 10n + BigInt(l1.val)) % 1000000007n; l1 = l1.next; }
  while (l2) { n2 = (n2 * 10n + BigInt(l2.val)) % 1000000007n; l2 = l2.next; }
  return Number((n1 * n2) % 1000000007n);
}

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

Loading discussion…

Saved in this browser only. Private to you.

JavaScript