VOOZH about

URL: https://www.geeksforgeeks.org/dsa/multiply-two-numbers-represented-linked-lists/

⇱ Multiply two numbers represented by Linked Lists - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Multiply two numbers represented by Linked Lists

Last Updated : 13 Sep, 2024

Given two numbers represented by linked lists, The task is to return the multiplication of these two linked lists.

Examples:

Input : head1 : 1->0->0 , head2 : 1->0
Output: 1000
Explanation: head1 represents 100 and head2 represents the number 10, 100 x 10 = 1000

👁 Image

Input : head1 : 3->2, head2 : 2
Output: 64
Explanation: head1 represents 32 and head2 represents the number 2, 32 x 2= 64

👁 Image

Approach:

To multiply two numbers represented by linked lists, you need to traverse each linked list from the head node to the end. For each linked list, initialize a variable to zero, which will be used to store the numerical value of the linked list. By processing each node, start by adding the value of the first node to this variable. For each subsequent node, multiply the variable by 10 and then add the node's value to it. This approach effectively reconstructs the number represented by the linked list. To handle potential overflow and ensure that the computations remain within manageable bounds, use the modulo operation with 1e9 + 7 after each arithmetic operation. This will keep the intermediate results within a safe range and prevent overflow during multiplication.

Below is the implementation of the above approach :


Output
79464

Time Complexity: O(max(n1, n2)), where n1 and n2 represents the number of nodes present in the first and second linked list respectively.
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: