Given the head of two singly linked lists that merge at some point to form a Y-shaped structure. The two lists may have different lengths and contain distinct nodes initially, but from the intersection point onward, they share the same sequence of nodes. Find the node at which the two linked lists first intersect.
Example:
Input:
Output: 8 Explanation: 8 is the first common node where both linked lists start sharing the same sequence of nodes.
[Naive Approach] Using two nested loops - O(m × n) Time and O(1) Space
The idea is to take each node of the first linked list and compare it with every node of the second list. The first common node that appears in both lists will be the intersection point.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};Node*intersectPoint(Node*head1,Node*head2){// Iterate over second list and for each node// Search it in first listwhile(head2!=nullptr){Node*temp=head1;while(temp){// If both Nodes are sameif(temp==head2)returnhead2;temp=temp->next;}head2=head2->next;}// intersection is not present between the listsreturnnullptr;}intmain(){// creation of first list: 10 -> 15 -> 30Node*head1=newNode(10);head1->next=newNode(15);head1->next->next=newNode(30);// creation of second list: 3 -> 6 -> 9 -> 15 -> 30Node*head2=newNode(3);head2->next=newNode(6);head2->next->next=newNode(9);// 15 is the intersection pointhead2->next->next->next=head1->next;Node*intersectionPoint=intersectPoint(head1,head2);if(intersectionPoint==nullptr)cout<<"-1";elsecout<<intersectionPoint->data<<endl;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};structNode*createNode(intdata){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=data;newNode->next=NULL;returnnewNode;}structNode*intersectPoint(structNode*head1,structNode*head2){// iterate over second list and for each node// Search it in first listwhile(head2!=NULL){structNode*temp=head1;while(temp!=NULL){// if both Nodes are sameif(temp==head2)returnhead2;temp=temp->next;}head2=head2->next;}// intersection is not present between the listsreturnNULL;}intmain(){// creation of first list: 10 -> 15 -> 30structNode*head1=createNode(10);head1->next=createNode(15);head1->next->next=createNode(30);// creation of second list: 3 -> 6 -> 9 -> 15 -> 30structNode*head2=createNode(3);head2->next=createNode(6);head2->next->next=createNode(9);// 15 is the intersection pointhead2->next->next->next=head1->next;structNode*intersectionPoint=intersectPoint(head1,head2);if(intersectionPoint==NULL)printf("-1\n");elseprintf("%d\n",intersectionPoint->data);return0;}
Java
classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{staticNodeintersectPoint(Nodehead1,Nodehead2){// iterate over second list and for each node// Search it in first listwhile(head2!=null){Nodetemp=head1;while(temp!=null){// if both Nodes are sameif(temp==head2)returnhead2;temp=temp.next;}head2=head2.next;}// intersection is not present between the listsreturnnull;}publicstaticvoidmain(String[]args){// creation of first list: 10 -> 15 -> 30Nodehead1=newNode(10);head1.next=newNode(15);head1.next.next=newNode(30);// creation of second list: 3 -> 6 -> 9 -> 15 -> 30Nodehead2=newNode(3);head2.next=newNode(6);head2.next.next=newNode(9);// 15 is the intersection pointhead2.next.next.next=head1.next;NodeintersectionPoint=intersectPoint(head1,head2);if(intersectionPoint==null)System.out.println("-1");elseSystem.out.println(intersectionPoint.data);}}
Python
classNode:def__init__(self,x):self.data=xself.next=NonedefintersectPoint(head1,head2):# iterate over second list and for each node# Search it in first listwhilehead2isnotNone:temp=head1whiletempisnotNone:# If both Nodes are sameiftemp==head2:returnhead2temp=temp.nexthead2=head2.next# intersection is not present between the listsreturnNoneif__name__=="__main__":# creation of first list: 10 -> 15 -> 30head1=Node(10)head1.next=Node(15)head1.next.next=Node(30)# creation of second list: 3 -> 6 -> 9 -> 15 -> 30head2=Node(3)head2.next=Node(6)head2.next.next=Node(9)# 15 is the intersection pointhead2.next.next.next=head1.nextintersectionPoint=intersectPoint(head1,head2)ifintersectionPointisNone:print("-1")else:print(intersectionPoint.data)
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{staticNodeintersectPoint(Nodehead1,Nodehead2){// Iterate over second list and for each node// Search it in first listwhile(head2!=null){Nodetemp=head1;while(temp!=null){// If both Nodes are sameif(temp==head2)returnhead2;temp=temp.next;}head2=head2.next;}// intersection is not present between the listsreturnnull;}staticvoidMain(string[]args){// creation of first list: 10 -> 15 -> 30Nodehead1=newNode(10);head1.next=newNode(15);head1.next.next=newNode(30);// creation of second list: 3 -> 6 -> 9 -> 15 -> 30Nodehead2=newNode(3);head2.next=newNode(6);head2.next.next=newNode(9);// 15 is the intersection pointhead2.next.next.next=head1.next;NodeintersectionPoint=intersectPoint(head1,head2);if(intersectionPoint==null)Console.WriteLine("-1");elseConsole.WriteLine(intersectionPoint.data);}}
JavaScript
classNode{constructor(x){this.data=x;this.next=null;}}functionintersectPoint(head1,head2){// Iterate over second list and for each node// Search it in first listwhile(head2!==null){lettemp=head1;while(temp!==null){// If both Nodes are sameif(temp===head2)returnhead2;temp=temp.next;}head2=head2.next;}// Intersection is not present between the listsreturnnull;}// Driver Code// creation of first list: 10 -> 15 -> 30lethead1=newNode(10);head1.next=newNode(15);head1.next.next=newNode(30);// creation of second list: 3 -> 6 -> 9 -> 15 -> 30lethead2=newNode(3);head2.next=newNode(6);head2.next.next=newNode(9);// 15 is the intersection pointhead2.next.next.next=head1.next;constintersectionPoint=intersectPoint(head1,head2);if(intersectionPoint===null)console.log("-1");elseconsole.log(intersectionPoint.data);
Output
15
[Better Approach] Using Hashing - O(m + n) Time and O(m) Space
The idea is to use hashing to store all the nodes of the first list in a hash set and then iterate over second list checking if the node is present in the set. If we find a node which is present in the hash set, we return the node.
C++
#include<iostream>#include<unordered_set>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};Node*intersectPoint(Node*head1,Node*head2){unordered_set<Node*>visNodes;// traverse the first list and store all// nodes in a setNode*curr1=head1;while(curr1!=nullptr){visNodes.insert(curr1);curr1=curr1->next;}// traverse the second list and check if any// node is in the setNode*curr2=head2;while(curr2!=nullptr){if(visNodes.find(curr2)!=visNodes.end()){// Intersection point foundreturncurr2;}curr2=curr2->next;}returnnullptr;}intmain(){// creation of first list: 10 -> 15 -> 30Node*head1=newNode(10);head1->next=newNode(15);head1->next->next=newNode(30);// creation of second list// 3 -> 6 -> 9 -> 15 -> 30Node*head2=newNode(3);head2->next=newNode(6);head2->next->next=newNode(9);// 15 is the intersection pointhead2->next->next->next=head1->next;Node*interPt=intersectPoint(head1,head2);if(interPt==nullptr)cout<<"-1";elsecout<<interPt->data<<endl;}
Java
importjava.util.HashSet;classNode{intdata;Nodenext;Node(intnew_data){data=new_data;next=null;}}classGfG{staticNodeintersectPoint(Nodehead1,Nodehead2){HashSet<Node>visNodes=newHashSet<>();// Traverse the first list and store all nodes in a setNodecurr1=head1;while(curr1!=null){visNodes.add(curr1);curr1=curr1.next;}// Traverse the second list and check if any node is// in the setNodecurr2=head2;while(curr2!=null){if(visNodes.contains(curr2)){// Intersection point foundreturncurr2;}curr2=curr2.next;}returnnull;}publicstaticvoidmain(String[]args){// creation of first list: 10 -> 15 -> 30Nodehead1=newNode(10);head1.next=newNode(15);head1.next.next=newNode(30);// creation of second list: 3 -> 6 -> 9 -> 15 -> 30Nodehead2=newNode(3);head2.next=newNode(6);head2.next.next=newNode(9);// 15 is the intersection pointhead2.next.next.next=head1.next;NodeinterPt=intersectPoint(head1,head2);if(interPt==null)System.out.println("-1");elseSystem.out.println(interPt.data);}}
Python
classNode:def__init__(self,new_data):self.data=new_dataself.next=NonedefintersectPoint(head1,head2):visNodes=set()# Traverse the first list and store all nodes in a setcurr1=head1whilecurr1isnotNone:visNodes.add(curr1)curr1=curr1.next# Traverse the second list and check if any node is in the setcurr2=head2whilecurr2isnotNone:ifcurr2invisNodes:returncurr2# Intersection point foundcurr2=curr2.nextreturnNoneif__name__=="__main__":# creation of first list: 10 -> 15 -> 30head1=Node(10)head1.next=Node(15)head1.next.next=Node(30)# creation of second list: 3 -> 6 -> 9 -> 15 -> 30head2=Node(3)head2.next=Node(6)head2.next.next=Node(9)# 15 is the intersection pointhead2.next.next.next=head1.nextinterPt=intersectPoint(head1,head2)ifinterPtisNone:print("-1")else:print(interPt.data)
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodenext;publicNode(intnew_data){data=new_data;next=null;}}classGfG{staticNodeintersectPoint(Nodehead1,Nodehead2){HashSet<Node>visNodes=newHashSet<Node>();// Traverse the first list and store all nodes in a setNodecurr1=head1;while(curr1!=null){visNodes.Add(curr1);curr1=curr1.next;}// Traverse the second list and check if any node is// in the setNodecurr2=head2;while(curr2!=null){// Intersection point foundif(visNodes.Contains(curr2))returncurr2;curr2=curr2.next;}returnnull;}staticvoidMain(string[]args){// creation of first list: 10 -> 15 -> 30Nodehead1=newNode(10);head1.next=newNode(15);head1.next.next=newNode(30);// creation of second list: 3 -> 6 -> 9 -> 15 -> 30Nodehead2=newNode(3);head2.next=newNode(6);head2.next.next=newNode(9);// 15 is the intersection pointhead2.next.next.next=head1.next;NodeinterPt=intersectPoint(head1,head2);if(interPt==null)Console.WriteLine("-1");elseConsole.WriteLine(interPt.data);}}
JavaScript
classNode{constructor(data){this.data=data;this.next=null;}}functionintersectPoint(head1,head2){constvisNodes=newSet();// traverse the first list and store // all nodes in a setletcurr1=head1;while(curr1!==null){visNodes.add(curr1);curr1=curr1.next;}// traverse the second list and check// if any node is in// the setletcurr2=head2;while(curr2!==null){// intersection point foundif(visNodes.has(curr2)){returncurr2;}curr2=curr2.next;}returnnull;}// Driver Code// creation of first list: 10 -> 15 -> 30lethead1=newNode(10);head1.next=newNode(15);head1.next.next=newNode(30);// creation of second list// 3 -> 6 -> 9 -> 15 -> 30lethead2=newNode(3);head2.next=newNode(6);head2.next.next=newNode(9);// 15 is the intersection pointhead2.next.next.next=head1.next;constinterPt=intersectPoint(head1,head2);if(interPt===null)console.log("-1");elseconsole.log(interPt.data);
Output
15
[Expected Approach - 1] Using difference in node counts - O(m + n) Time and O(1) Space
The two lists share the same tail after the intersection; only their starting parts differ in length. To align them, we should skip the extra nodes in the longer list so both pointers stand at the same distance from the intersection.
Count the nodes in both lists and find the difference (d). Advance the pointer of the longer list by d steps, then move both pointers together until they meet. The meeting point is the intersection.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// function to get the count of nodes in a linked list intgetCount(Node*head){intcnt=0;Node*curr=head;while(curr!=nullptr){cnt++;curr=curr->next;}returncnt;}// function to get the intersection point of two// linked lists where head1 has d more nodes than head2Node*getIntersectionByDiff(intdiff,Node*head1,Node*head2){Node*curr1=head1;Node*curr2=head2;// move the pointer forward by d nodesfor(inti=0;i<diff;i++){if(curr1==nullptr)returnnullptr;curr1=curr1->next;}// move both pointers until they intersectwhile(curr1!=nullptr&&curr2!=nullptr){if(curr1==curr2)returncurr1;curr1=curr1->next;curr2=curr2->next;}returnnullptr;}// function to get the intersection point of two linked listsNode*intersectPoint(Node*head1,Node*head2){// count the number of nodes in both linked listsintlen1=getCount(head1);intlen2=getCount(head2);intdiff=0;// if the first list is longerif(len1>len2){diff=len1-len2;returngetIntersectionByDiff(diff,head1,head2);}else{diff=len2-len1;returngetIntersectionByDiff(diff,head2,head1);}}intmain(){// creation of first list: 10 -> 15 -> 30Node*head1=newNode(10);head1->next=newNode(15);head1->next->next=newNode(30);// creation of second list: 3 -> 6 -> 9 -> 15 -> 30Node*head2=newNode(3);head2->next=newNode(6);head2->next->next=newNode(9);// 15 is the intersection pointhead2->next->next->next=head1->next;Node*interPt=intersectPoint(head1,head2);if(interPt==nullptr)cout<<"-1";elsecout<<interPt->data<<endl;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};structNode*createNode(intdata){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=data;newNode->next=NULL;returnnewNode;}// Function to get the count of nodes in a linked list intgetCount(structNode*head){intcnt=0;structNode*curr=head;while(curr!=NULL){cnt++;curr=curr->next;}returncnt;}// Function to get the intersection point of two// linked lists where head1 has d more nodes than head2structNode*getIntersectionByDiff(intdiff,structNode*head1,structNode*head2){structNode*curr1=head1;structNode*curr2=head2;// Move the pointer forward by d nodesfor(inti=0;i<diff;i++){if(curr1==NULL)returnNULL;curr1=curr1->next;}// Move both pointers until they intersectwhile(curr1!=NULL&&curr2!=NULL){if(curr1==curr2)returncurr1;curr1=curr1->next;curr2=curr2->next;}returnNULL;}// Function to get the intersection point of two linked listsstructNode*intersectPoint(structNode*head1,structNode*head2){// Count the number of nodes in both linked listsintlen1=getCount(head1);intlen2=getCount(head2);intdiff=0;// If the first list is longerif(len1>len2){diff=len1-len2;returngetIntersectionByDiff(diff,head1,head2);}else{diff=len2-len1;returngetIntersectionByDiff(diff,head2,head1);}}intmain(){// creation of first list: 10 -> 15 -> 30structNode*head1=createNode(10);head1->next=createNode(15);head1->next->next=createNode(30);// creation of second list: 3 -> 6 -> 9 -> 15 -> 30structNode*head2=createNode(3);head2->next=createNode(6);head2->next->next=createNode(9);// 15 is the intersection pointhead2->next->next->next=head1->next;structNode*interPt=intersectPoint(head1,head2);if(interPt==NULL)printf("-1\n");elseprintf("%d\n",interPt->data);return0;}
Java
classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{// Function to get the count of nodes in a linked list staticintgetCount(Nodehead){intcnt=0;Nodecurr=head;while(curr!=null){cnt++;curr=curr.next;}returncnt;}// Function to get the intersection point of two// linked lists where head1 has d more nodes than head2staticNodegetIntersectionByDiff(intdiff,Nodehead1,Nodehead2){Nodecurr1=head1;Nodecurr2=head2;// Move the pointer forward by d nodesfor(inti=0;i<diff;i++){if(curr1==null)returnnull;curr1=curr1.next;}// Move both pointers until they intersectwhile(curr1!=null&&curr2!=null){if(curr1==curr2)returncurr1;curr1=curr1.next;curr2=curr2.next;}returnnull;}// Function to get the intersection point of two linked listsstaticNodeintersectPoint(Nodehead1,Nodehead2){// Count the number of nodes in both linked listsintlen1=getCount(head1);intlen2=getCount(head2);intdiff=0;// If the first list is longerif(len1>len2){diff=len1-len2;returngetIntersectionByDiff(diff,head1,head2);}else{diff=len2-len1;returngetIntersectionByDiff(diff,head2,head1);}}publicstaticvoidmain(String[]args){// creation of first list: 10 -> 15 -> 30Nodehead1=newNode(10);head1.next=newNode(15);head1.next.next=newNode(30);// creation of second list: 3 -> 6 -> 9 -> 15 -> 30Nodehead2=newNode(3);head2.next=newNode(6);head2.next.next=newNode(9);// 15 is the intersection pointhead2.next.next.next=head1.next;NodeinterPt=intersectPoint(head1,head2);if(interPt==null)System.out.println("-1");elseSystem.out.println(interPt.data);}}
Python
classNode:def__init__(self,data):self.data=dataself.next=None# Function to get the count of nodes in a linked list defgetCount(head):cnt=0curr=headwhilecurr:cnt+=1curr=curr.nextreturncnt# Function to get the intersection point of two# linked lists where head1 has d more nodes than head2defgetIntersectionByDiff(diff,head1,head2):curr1=head1curr2=head2# Move the pointer forward by d nodesfor_inrange(diff):ifnotcurr1:returnNonecurr1=curr1.next# Move both pointers until they intersectwhilecurr1andcurr2:ifcurr1==curr2:returncurr1curr1=curr1.nextcurr2=curr2.nextreturnNone# Function to get the intersection point of two linked listsdefintersectPoint(head1,head2):# Count the number of nodes in both linked listslen1=getCount(head1)len2=getCount(head2)diff=0# If the first list is longeriflen1>len2:diff=len1-len2returngetIntersectionByDiff(diff,head1,head2)else:diff=len2-len1returngetIntersectionByDiff(diff,head2,head1)if__name__=="__main__":# creation of first list: 10 -> 15 -> 30head1=Node(10)head1.next=Node(15)head1.next.next=Node(30)# creation of second list: 3 -> 6 -> 9 -> 15 -> 30head2=Node(3)head2.next=Node(6)head2.next.next=Node(9)# 15 is the intersection pointhead2.next.next.next=head1.nextinterPt=intersectPoint(head1,head2)ifnotinterPt:print("-1")else:print(interPt.data)
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Function to get the count of nodes in a linked list staticintgetCount(Nodehead){intcnt=0;Nodecurr=head;while(curr!=null){cnt++;curr=curr.next;}returncnt;}// Function to get the intersection point of two// linked lists where head1 has d more nodes than head2staticNodegetIntersectionByDiff(intdiff,Nodehead1,Nodehead2){Nodecurr1=head1;Nodecurr2=head2;// Move the pointer forward by d nodesfor(inti=0;i<diff;i++){if(curr1==null)returnnull;curr1=curr1.next;}// Move both pointers until they intersectwhile(curr1!=null&&curr2!=null){if(curr1==curr2)returncurr1;curr1=curr1.next;curr2=curr2.next;}returnnull;}// Function to get the intersection point of two linked listsstaticNodeintersectPoint(Nodehead1,Nodehead2){// Count the number of nodes in both linked listsintlen1=getCount(head1);intlen2=getCount(head2);intdiff=0;// If the first list is longerif(len1>len2){diff=len1-len2;returngetIntersectionByDiff(diff,head1,head2);}else{diff=len2-len1;returngetIntersectionByDiff(diff,head2,head1);}}staticvoidMain(string[]args){// creation of first list: 10 -> 15 -> 30Nodehead1=newNode(10);head1.next=newNode(15);head1.next.next=newNode(30);// creation of second list: 3 -> 6 -> 9 -> 15 -> 30Nodehead2=newNode(3);head2.next=newNode(6);head2.next.next=newNode(9);// 15 is the intersection pointhead2.next.next.next=head1.next;NodeinterPt=intersectPoint(head1,head2);if(interPt==null)Console.WriteLine("-1");elseConsole.WriteLine(interPt.data);}}
JavaScript
classNode{constructor(x){this.data=x;this.next=null;}}// Function to get the count of nodes in a linked list functiongetCount(head){letcnt=0;letcurr=head;while(curr!==null){cnt++;curr=curr.next;}returncnt;}// Function to get the intersection point of two// linked lists where head1 has d more nodes than head2functiongetIntersectionByDiff(diff,head1,head2){letcurr1=head1;letcurr2=head2;// Move the pointer forward by d nodesfor(leti=0;i<diff;i++){if(curr1===null)returnnull;curr1=curr1.next;}// Move both pointers until they intersectwhile(curr1!==null&&curr2!==null){if(curr1===curr2)returncurr1;curr1=curr1.next;curr2=curr2.next;}returnnull;}// Function to get the intersection point of two linked listsfunctionintersectPoint(head1,head2){// Count the number of nodes in both linked listsletlen1=getCount(head1);letlen2=getCount(head2);letdiff=0;// If the first list is longerif(len1>len2){diff=len1-len2;returngetIntersectionByDiff(diff,head1,head2);}else{diff=len2-len1;returngetIntersectionByDiff(diff,head2,head1);}}// Driver Code// creation of first list: 10 -> 15 -> 30lethead1=newNode(10);head1.next=newNode(15);head1.next.next=newNode(30);// creation of second list: 3 -> 6 -> 9 -> 15 -> 30lethead2=newNode(3);head2.next=newNode(6);head2.next.next=newNode(9);// 15 is the intersection pointhead2.next.next.next=head1.next;letinterPt=intersectPoint(head1,head2);if(interPt===null)console.log("-1");elseconsole.log(interPt.data);
Output
15
[Expected Approach - 2] Using Two Pointer Technique - O(m + n) Time and O(1) Space
The idea is to traverse the two given linked lists simultaneously, using two pointers. When one pointer reaches the end of its list, it is reassigned to the head of the other list. This process continues until the two pointers meet, which indicates that they have reached the intersection point.
Why this works:
Suppose the lengths of the two lists are m and n, and they share a common tail of length c.
The unique parts before the intersection are m - c and n - c.
By switching lists, each pointer travels (m - c) + c + (n - c) = m + n - c steps before reaching the intersection.
Since both pointers cover exactly m + n - c steps, they must arrive at the intersection at the same time.
Step by Step Approach:
Initialize two pointers ptr1 and ptr2 at head1 and head2 respectively.
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 at equal distance 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, returns NULL.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};Node*intersectPoint(Node*head1,Node*head2){Node*ptr1=head1;Node*ptr2=head2;if(ptr1==nullptr||ptr2==nullptr)returnnullptr;// traverse through the lists until both pointers meetwhile(ptr1!=ptr2){// move to the next node in each list and if the one // pointer reaches NULL, start from the other linked listptr1=ptr1?ptr1->next:head2;ptr2=ptr2?ptr2->next:head1;}returnptr1;}intmain(){// creation of first list: 10 -> 15 -> 30Node*head1=newNode(10);head1->next=newNode(15);head1->next->next=newNode(30);// creation of second list: 3 -> 6 -> 9 -> 15 -> 30Node*head2=newNode(3);head2->next=newNode(6);head2->next->next=newNode(9);// 15 is the intersection pointhead2->next->next->next=head1->next;Node*interPt=intersectPoint(head1,head2);if(interPt==nullptr)cout<<"-1";elsecout<<interPt->data<<endl;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};structNode*createNode(intdata){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=data;newNode->next=NULL;returnnewNode;}structNode*intersectPoint(structNode*head1,structNode*head2){structNode*ptr1=head1;structNode*ptr2=head2;if(ptr1==NULL||ptr2==NULL)returnNULL;// Traverse through the lists until both pointers meetwhile(ptr1!=ptr2){ptr1=ptr1?ptr1->next:head2;ptr2=ptr2?ptr2->next:head1;}returnptr1;}intmain(){// creation of first list: 10 -> 15 -> 30structNode*head1=createNode(10);head1->next=createNode(15);head1->next->next=createNode(30);// creation of second list: 3 -> 6 -> 9 -> 15 -> 30structNode*head2=createNode(3);head2->next=createNode(6);head2->next->next=createNode(9);// 15 is the intersection pointhead2->next->next->next=head1->next;structNode*interPt=intersectPoint(head1,head2);if(interPt==NULL)printf("-1\n");elseprintf("%d\n",interPt->data);return0;}
Java
classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{staticNodeintersectPoint(Nodehead1,Nodehead2){Nodeptr1=head1;Nodeptr2=head2;if(ptr1==null||ptr2==null)returnnull;// traverse through the lists until both// pointers meetwhile(ptr1!=ptr2){// move to the next node in each list and if the one // pointer reaches NULL, start from the other linked listptr1=(ptr1!=null)?ptr1.next:head2;ptr2=(ptr2!=null)?ptr2.next:head1;}returnptr1;}publicstaticvoidmain(String[]args){// creation of first list: 10 -> 15 -> 30Nodehead1=newNode(10);head1.next=newNode(15);head1.next.next=newNode(30);// creation of second list: 3 -> 6 -> 9 -> 15 -> 30Nodehead2=newNode(3);head2.next=newNode(6);head2.next.next=newNode(9);// 15 is the intersection pointhead2.next.next.next=head1.next;NodeinterPt=intersectPoint(head1,head2);if(interPt==null)System.out.println("-1");elseSystem.out.println(interPt.data);}}
Python
classNode:def__init__(self,data):self.data=dataself.next=NonedefintersectPoint(head1,head2):ptr1=head1ptr2=head2ifnotptr1ornotptr2:returnNone# traverse through the lists until both pointers meetwhileptr1!=ptr2:# move to the next node in each list and if the one # pointer reaches None, start from the other linked listptr1=ptr1.nextifptr1elsehead2ptr2=ptr2.nextifptr2elsehead1returnptr1if__name__=="__main__":# creation of first list: 10 -> 15 -> 30head1=Node(10)head1.next=Node(15)head1.next.next=Node(30)# creation of second list: 3 -> 6 -> 9 -> 15 -> 30head2=Node(3)head2.next=Node(6)head2.next.next=Node(9)# 15 is the intersection pointhead2.next.next.next=head1.nextinterPt=intersectPoint(head1,head2)ifnotinterPt:print("-1")else:print(interPt.data)
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{staticNodeintersectPoint(Nodehead1,Nodehead2){Nodeptr1=head1;Nodeptr2=head2;if(ptr1==null||ptr2==null)returnnull;// traverse through the lists until both pointers meetwhile(ptr1!=ptr2){// move to the next node in each list and if the one // pointer reaches null, start from the other linked listptr1=(ptr1!=null)?ptr1.next:head2;ptr2=(ptr2!=null)?ptr2.next:head1;}returnptr1;}publicstaticvoidMain(string[]args){// creation of first list: 10 -> 15 -> 30Nodehead1=newNode(10);head1.next=newNode(15);head1.next.next=newNode(30);// creation of second list: 3 -> 6 -> 9 -> 15 -> 30Nodehead2=newNode(3);head2.next=newNode(6);head2.next.next=newNode(9);// 15 is the intersection pointhead2.next.next.next=head1.next;NodeinterPt=intersectPoint(head1,head2);if(interPt==null)Console.WriteLine("-1");elseConsole.WriteLine(interPt.data);}}
JavaScript
classNode{constructor(x){this.data=x;this.next=null;}}functionintersectPoint(head1,head2){letptr1=head1;letptr2=head2;if(!ptr1||!ptr2)returnnull;// traverse through the lists until both// pointers meetwhile(ptr1!==ptr2){// move to the next node in each list and if the one // pointer reaches null, start from the other linked listptr1=ptr1?ptr1.next:head2;ptr2=ptr2?ptr2.next:head1;}returnptr1;}// Driver Code// creation of first list: 10 -> 15 -> 30lethead1=newNode(10);head1.next=newNode(15);head1.next.next=newNode(30);// creation of second list: 3 -> 6 -> 9 -> 15 -> 30lethead2=newNode(3);head2.next=newNode(6);head2.next.next=newNode(9);// 15 is the intersection pointhead2.next.next.next=head1.next;letinterPt=intersectPoint(head1,head2);if(!interPt)console.log("-1");elseconsole.log(interPt.data);
Output
15
[Expected Approach - 3] Intersection Detection using Floyd’s Cycle-Finding Algorithm
If two linked lists intersect, the intersection point is the place where their paths merge into one. One way to detect this is to convert the problem into a cycle detection problem. If we somehow make the shared portion of the two lists form a loop, then standard cycle detection techniques can be applied to locate the intersection.
To achieve this, we connect the second list to the end of the first list. If the lists intersect, this connection will create a cycle and first node of cycle will be our intersection point.
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// finds the intersection point of two// linked listsNode*intersectPoint(Node*head1,Node*head2){if(!head1||!head2)returnnullptr;// attach second list to the// end of the firstNode*temp=head1;while(temp->next)temp=temp->next;temp->next=head2;// detect cycle using Floyd’s algorithmNode*slow=head1;Node*fast=head1;while(fast&&fast->next){slow=slow->next;fast=fast->next->next;if(slow==fast){slow=head1;while(slow!=fast){slow=slow->next;fast=fast->next;}returnslow;}}returnnullptr;}intmain(){// first list: 10 -> 15 -> 30Node*head1=newNode(10);head1->next=newNode(15);head1->next->next=newNode(30);// second list: 3 -> 6 -> 9 -> 15 -> 30Node*head2=newNode(3);head2->next=newNode(6);head2->next->next=newNode(9);// intersection at node with value 15head2->next->next->next=head1->next;Node*interPt=intersectPoint(head1,head2);if(interPt==nullptr)cout<<"-1";elsecout<<interPt->data<<endl;}
Java
importjava.util.*;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}publicclassMain{// finds the intersection point of two// linked listspublicstaticNodeintersectPoint(Nodehead1,Nodehead2){if(head1==null||head2==null)returnnull;// attach second list to the// end of the firstNodetemp=head1;while(temp.next!=null)temp=temp.next;temp.next=head2;// detect cycle using Floyd’s algorithmNodeslow=head1;Nodefast=head1;while(fast!=null&&fast.next!=null){slow=slow.next;fast=fast.next.next;if(slow==fast){slow=head1;while(slow!=fast){slow=slow.next;fast=fast.next;}returnslow;}}returnnull;}publicstaticvoidmain(String[]args){// first list: 10 -> 15 -> 30Nodehead1=newNode(10);head1.next=newNode(15);head1.next.next=newNode(30);// second list: 3 -> 6 -> 9 -> 15 -> 30Nodehead2=newNode(3);head2.next=newNode(6);head2.next.next=newNode(9);// intersection at node with value 15head2.next.next.next=head1.next;NodeinterPt=intersectPoint(head1,head2);if(interPt==null)System.out.print("-1");elseSystem.out.println(interPt.data);}}
Python
classNode:def__init__(self,x):self.data=xself.next=None# finds the intersection point of two# linked listsdefintersect_point(head1,head2):ifnothead1ornothead2:returnNone# attach second list to the# end of the firsttemp=head1whiletemp.next:temp=temp.nexttemp.next=head2# detect cycle using Floyd’s algorithmslow=head1fast=head1whilefastandfast.next:slow=slow.nextfast=fast.next.nextifslow==fast:slow=head1whileslow!=fast:slow=slow.nextfast=fast.nextreturnslowreturnNoneif__name__=='__main__':# first list: 10 -> 15 -> 30head1=Node(10)head1.next=Node(15)head1.next.next=Node(30)# second list: 3 -> 6 -> 9 -> 15 -> 30head2=Node(3)head2.next=Node(6)head2.next.next=Node(9)# intersection at node with value 15head2.next.next.next=head1.nextinter_pt=intersect_point(head1,head2)ifinter_ptisNone:print("-1")else:print(inter_pt.data)
C#
usingSystem;publicclassNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}publicclassProgram{// finds the intersection point of two// linked listspublicstaticNodeIntersectPoint(Nodehead1,Nodehead2){if(head1==null||head2==null)returnnull;// attach second list to the// end of the firstNodetemp=head1;while(temp.next!=null)temp=temp.next;temp.next=head2;// detect cycle using Floyd’s algorithmNodeslow=head1;Nodefast=head1;while(fast!=null&&fast.next!=null){slow=slow.next;fast=fast.next.next;if(slow==fast){slow=head1;while(slow!=fast){slow=slow.next;fast=fast.next;}returnslow;}}returnnull;}publicstaticvoidMain(){// first list: 10 -> 15 -> 30Nodehead1=newNode(10);head1.next=newNode(15);head1.next.next=newNode(30);// second list: 3 -> 6 -> 9 -> 15 -> 30Nodehead2=newNode(3);head2.next=newNode(6);head2.next.next=newNode(9);// intersection at node with value 15head2.next.next.next=head1.next;NodeinterPt=IntersectPoint(head1,head2);if(interPt==null)Console.Write("-1");elseConsole.WriteLine(interPt.data);}}
JavaScript
classNode{constructor(x){this.data=x;this.next=null;}}// finds the intersection point of two// linked listsfunctionintersectPoint(head1,head2){if(!head1||!head2)returnnull;// attach second list to the// end of the firstlettemp=head1;while(temp.next){temp=temp.next;}temp.next=head2;// detect cycle using Floyd’s algorithmletslow=head1;letfast=head1;while(fast&&fast.next){slow=slow.next;fast=fast.next.next;if(slow===fast){slow=head1;while(slow!==fast){slow=slow.next;fast=fast.next;}returnslow;}}returnnull;}// first list: 10 -> 15 -> 30lethead1=newNode(10);head1.next=newNode(15);head1.next.next=newNode(30);// second list: 3 -> 6 -> 9 -> 15 -> 30lethead2=newNode(3);head2.next=newNode(6);head2.next.next=newNode(9);// intersection at node with value 15head2.next.next.next=head1.next;letinterPt=intersectPoint(head1,head2);if(interPt===null)console.log("-1");elseconsole.log(interPt.data);
Output
15
Time Complexity: O(m + n), where m and n are the lengths of the two linked lists. Running Floyd’s cycle detection take linear time in the size of the lists. Auxiliary Space: O(1)