Multiply two numbers represented by Linked Lists Easy 0 attempts
GeeksforGeeks ↗

Multiply two numbers represented by Linked Lists

Easy Linked List GeeksforGeeks

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.

Input Format
Implement multiplyLists(l1, l2). Inputs below show JavaScript function arguments; there is no stdin parsing. Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.
Output Format
Return the result described in the statement.

Sample Input and Output

Example 1 ยท Run Sample

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
Test Cases (2)
Case 1
Args: [[3,2],[2]] Expected: 64
Case 2
Args: [[0],[9,9]] Expected: 0
Topics

Accumulate Digits Modulo 10^9 + 7

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)

Saved in this browser only. Private to you.

JavaScript