Open in App
Not now

# Write a function to get the intersection point of two Linked Lists

• Difficulty Level : Medium
• Last Updated : 22 Mar, 2023

There are two singly linked lists in a system. By some programming error, the end node of one of the linked lists got linked to the second list, forming an inverted Y-shaped list. Write a program to get the point where two linked lists merge.

Intersection Point of Two Linked Lists

The above diagram shows an example with two linked lists having 15 as intersection points.

Method 1(Simply use two loops):
Use 2 nested for loops. The outer loop will be for each node of the 1st list and the inner loop will be for the 2nd list. In the inner loop, check if any of the nodes of the 2nd list is the same as the current node of the first linked list. The time complexity of this method will be O(M * N) where m and n are the numbers of nodes in two lists.

Below is the code for the above approach:

## Javascript

Output

Intersection Point: 15

Time Complexity: O(m*n), where m and n are number of nodes in two linked list.
Auxiliary Space: O(1), Constant Space is used.

Method 2 (Mark Visited Nodes):
This solution requires modifications to the basic linked list data structure. Have a visited flag with each node. Traverse the first linked list and keep marking visited nodes. Now traverse the second linked list, If you see a visited node again then there is an intersection point, return the intersecting node. This solution works in O(m+n) but requires additional information with each node. A variation of this solution that doesnâ€™t require modification to the basic data structure can be implemented using a hash. Traverse the first linked list and store the addresses of visited nodes in a hash. Now traverse the second linked list and if you see an address that already exists in the hash then return the intersecting node.

## Javascript

Output

The node of intersection is : 4

Method 3(Using the difference in node counts)

• Get the count of the nodes in the first list, let the count be c1.
• Get the count of the nodes in the second list, let the count be c2.
• Get the difference of counts d = abs(c1 – c2)
• Now traverse the bigger list from the first node to d nodes so that from here onwards both the lists have an equal no of nodes
• Then we can traverse both lists in parallel till we come across a common node. (Note that getting a common node is done by comparing the address of the nodes)

Below image is a dry run of the above approach:

Step 1:  Traverse the bigger list from the first node to d nodes so that from here onwards both the lists have an equal no of nodes

Step 1

Step 2:  Traverse both lists in parallel till we come across a common node

Step 2

Below is the implementation of the above approach :

## Javascript



Output

The node of intersection is 15

Time Complexity: O(m+n)
Auxiliary Space: O(1)

Method 4(Make a circle in the first list)
Thanks to Saravanan Man for providing the below solution.
1. Traverse the first linked list(count the elements) and make a circular linked list. (Remember the last node so that we can break the circle later on).
2. Now view the problem as finding the loop in the second linked list. So the problem is solved.
3. Since we already know the length of the loop(size of the first linked list) we can traverse those many numbers of nodes in the second list, and then start another pointer from the beginning of the second list. we have to traverse until they are equal, and that is the required intersection point.
4. remove the circle from the linked list.

Time Complexity: O(m+n)
Auxiliary Space: O(1)

Method 5 (Reverse the first list and make equations)
Thanks to Saravanan Mani for providing this method.

1) Let X be the length of the first linked list until intersection point.
Let Y be the length of the second linked list until the intersection point.
Let Z be the length of the linked list from the intersection point to End of
the linked list including the intersection node.
We Have
X + Z = C1;
Y + Z = C2;
3) Traverse Second linked list. Let C3 be the length of second list - 1.
Now we have
X + Y = C3
We have 3 linear equations. By solving them, we get
X = (C1 + C3 â€“ C2)/2;
Y = (C2 + C3 â€“ C1)/2;
Z = (C1 + C2 â€“ C3)/2;
WE GOT THE INTERSECTION POINT.

Time complexity: O(m+n)
Auxiliary Space: O(1)

Method 6 (Traverse both lists and compare addresses of last nodes) This method is only to detect if there is an intersection point or not. (Thanks to NeoTheSaviour for suggesting this)

1) Traverse the list 1, store the last node address
2) Traverse the list 2, store the last node address.
3) If nodes stored in 1 and 2 are same then they are intersecting.

Time Complexity: O(m+n)
Auxiliary Space: O(1)

Method 7 (Use Hashing)
Basically, we need to find a common node of two linked lists. So we hash all nodes of the first list and then check the second list.
1) Create an empty hash set.
2) Traverse the first linked list and insert all nodes’ addresses in the hash set.
3) Traverse the second list. For every node check if it is present in the hash set. If we find a node in the hash set, return the node.

## C++

 // C++ program to get intersection point of two linked list #include #include using namespace std; class Node { public:     int data;     Node* next;       Node(int d)     {       data = d;       next = NULL;     } };   // function to find the intersection point of two lists void MegeNode(Node* n1, Node* n2) {     unordered_set hs;     while (n1 != NULL) {         hs.insert(n1);         n1 = n1->next;     }     while (n2) {         if (hs.find(n2) != hs.end()) {             cout << n2->data << endl;             break;         }         n2 = n2->next;     } }   // function to print the list void Print(Node* n) {       Node* curr = n;       while(curr != NULL){       cout << curr->data << " ";       curr = curr->next;     }       cout << endl; }     int main() {      // list 1      Node* n1 = new Node(1);      n1->next = new Node(2);      n1->next->next = new Node(3);      n1->next->next->next = new Node(4);      n1->next->next->next->next = new Node(5);      n1->next->next->next->next->next = new Node(6);      n1->next->next->next->next->next->next = new Node(7);      // list 2      Node* n2 = new Node(10);      n2->next = new Node(9);      n2->next->next = new Node(8);      n2->next->next->next = n1->next->next->next;      Print(n1);      Print(n2);                    MegeNode(n1,n2);                return 0; }    // This code is contributed by Upendra

## Java

 // Java program to get intersection point of two linked list import java.util.*; class Node {     int data;     Node next;     Node(int d)     {         data = d;         next = null;     } } class LinkedListIntersect {     public static void main(String[] args)     {         // list 1         Node n1 = new Node(1);         n1.next = new Node(2);         n1.next.next = new Node(3);         n1.next.next.next = new Node(4);         n1.next.next.next.next = new Node(5);         n1.next.next.next.next.next = new Node(6);         n1.next.next.next.next.next.next = new Node(7);         // list 2         Node n2 = new Node(10);         n2.next = new Node(9);         n2.next.next = new Node(8);         n2.next.next.next = n1.next.next.next;         Print(n1);         Print(n2);         System.out.println(MegeNode(n1, n2).data);     }       // function to print the list     public static void Print(Node n)     {         Node cur = n;         while (cur != null) {             System.out.print(cur.data + "  ");             cur = cur.next;         }         System.out.println();     }       // function to find the intersection of two node     public static Node MegeNode(Node n1, Node n2)     {         // define hashset         HashSet hs = new HashSet();         while (n1 != null) {             hs.add(n1);             n1 = n1.next;         }         while (n2 != null) {             if (hs.contains(n2)) {                 return n2;             }             n2 = n2.next;         }         return null;     } }

## Python3

 # Python program to get intersection # point of two linked list class Node :     def __init__(self, d):         self.data = d;         self.next = None;   # Function to print the list def Print(n):     cur = n;     while (cur != None) :         print(cur.data, end=" ");         cur = cur.next;     print("");   # Function to find the intersection of two node def MegeNode(n1, n2):           # Define hashset     hs = set();       while (n1 != None):         hs.add(n1);         n1 = n1.next;     while (n2 != None):         if (n2 in hs):             return n2;         n2 = n2.next;           return None;     # Driver code   # list 1 n1 = Node(1); n1.next = Node(2); n1.next.next = Node(3); n1.next.next.next = Node(4); n1.next.next.next.next = Node(5); n1.next.next.next.next.next = Node(6); n1.next.next.next.next.next.next = Node(7);   # list 2 n2 = Node(10); n2.next = Node(9); n2.next.next = Node(8); n2.next.next.next = n1.next.next.next;   Print(n1); Print(n2);   print(MegeNode(n1, n2).data);   # This code is contributed by _saurabh_jaiswal

## C#

 // C# program to get intersection point of two linked list using System; using System.Collections.Generic;   public class Node {     public int data;     public Node next;     public Node(int d)     {         data = d;         next = null;     } } public class LinkedListIntersect {     public static void Main(String[] args)     {         // list 1         Node n1 = new Node(1);         n1.next = new Node(2);         n1.next.next = new Node(3);         n1.next.next.next = new Node(4);         n1.next.next.next.next = new Node(5);         n1.next.next.next.next.next = new Node(6);         n1.next.next.next.next.next.next = new Node(7);         // list 2         Node n2 = new Node(10);         n2.next = new Node(9);         n2.next.next = new Node(8);         n2.next.next.next = n1.next.next.next;         Print(n1);         Print(n2);         Console.WriteLine(MegeNode(n1, n2).data);     }       // function to print the list     public static void Print(Node n)     {         Node cur = n;         while (cur != null)         {             Console.Write(cur.data + " ");             cur = cur.next;         }         Console.WriteLine();     }       // function to find the intersection of two node     public static Node MegeNode(Node n1, Node n2)     {         // define hashset         HashSet hs = new HashSet();         while (n1 != null)         {             hs.Add(n1);             n1 = n1.next;         }         while (n2 != null)         {             if (hs.Contains(n2))             {                 return n2;             }             n2 = n2.next;         }         return null;     } }   // This code is contributed by 29AjayKumar

## Javascript



Output

1 2 3 4 5 6 7
10 9 8 4 5 6 7
4

The time complexity of this solution is O(n) where n is the length of the longer list. This is because we need to traverse both of the linked lists in order to find the intersection point.  And space complexity is O(n) , because we are using unordered set.

Method 8( 2-pointer technique ):

Using Two pointers :

• Traverse through the lists, one node at a time.
• When ptr1 reaches the end of a list, then redirect it to head2.
• similarly, when ptr2 reaches the end of a list, redirect it to the head1.
• Once both of them go through reassigning, they will be equidistant from
the collision point
• If at any node ptr1 meets ptr2, then it is the intersection node.
• After the second iteration if there is no intersection node it returns NULL.

## Javascript



Output

INTERSEPOINT LIST :15->30

Time complexity : O( m + n )
Auxiliary Space:  O(1)

Method 9 : Using the 2-stack approach :

• Create 2 stacks.
• Iterate both the lists till the end and keep on adding the nodes of the list to the respective stack.
• If the last nodes are not equal. return saying no intersection.
• Iteratively check the stack tops. If equal, pop or else return the current node.

## Javascript

Output

INTERSECTION POINT :15

Time Complexity: O(M + N), where N and M are the length of the two lists.
Auxiliary Space: O(M + N)

Please write comments if you find any bug in the above algorithm or a better way to solve the same problem.

My Personal Notes arrow_drop_up
Related Articles