Intersecton of Y Linked List
Problem Statement:β
Given the head of two singly linked lists, return the point where these two linked lists intersect.
Note: It is guaranteed that the intersected node always exists.
-
Example:
β Solution 1: Length Difference Methodβ
class Solution {
public:
int getLength(Node *head1, Node *head2) {
int len1 = 0, len2 = 0;
while(head1 || head2) {
if(head1) {
len1++;
head1 = head1->next;
}
if(head2) {
len2++;
head2 = head2->next;
}
}
return len1 - len2;
}
Node* intersectPoint(Node* head1, Node* head2) {
if(head1 == NULL || head2 == NULL) return NULL;
int diff = getLength(head1, head2);
// Move longer list's pointer ahead by the diff
if(diff < 0) {
while(diff--) head2 = head2->next;
} else {
while(diff--) head1 = head1->next;
}
// Move both pointers together until they meet
while(head1 && head2) {
if(head1 == head2) return head1;
head1 = head1->next;
head2 = head2->next;
}
return NULL;
}
};
β Solution 2: Two Pointer Switching (Optimal)β
class Solution {
public:
Node* intersectPoint(Node* head1, Node* head2) {
Node *temp1 = head1, *temp2 = head2;
while(temp1 != temp2) {
temp1 = (temp1 == NULL) ? head2 : temp1->next;
temp2 = (temp2 == NULL) ? head1 : temp2->next;
}
return temp1; // Either intersection node or NULL
}
};
π How It Worksβ
Length Difference Approachβ
- Traverse both lists to calculate their lengths.
- Move the longer listβs pointer ahead by the length difference.
- Then move both pointers together until they meet.
Two Pointer Switchingβ
- When a pointer reaches the end, redirect it to the head of the other list.
- This ensures both pointers traverse equal total length.
- If they intersect, they meet at the node.
- If not, both become
NULLtogether.
π§© Key Insightβ
Two pointer switching ensures both pointers travel equal distance:
a + b + c == b + a + cWhere:
a= distance to intersection from head1b= distance to intersection from head2c= shared tail (intersection onward)
β±οΈ Time & Space Complexityβ
| Approach | Time | Space |
|---|---|---|
| Length Difference | O(N + M) | O(1) |
| Two Pointer Switching β | O(N + M) | O(1) |
Where N and M are the lengths of the two lists.
β οΈ Edge Casesβ
- β
No intersection β both reach
NULLand returnNULL - β
One or both lists are
NULLβ returnsNULL - β Intersection at head β both pointers point to same node immediately
π‘ Other Approachesβ
| Approach | Time | Space | Notes |
|---|---|---|---|
| Hashing | O(N + M) | O(N) | Store visited nodes from list1 and check list2 |
| Length Diff β | O(N + M) | O(1) | Simple logic |
| Two Pointer β | O(N + M) | O(1) | Elegant, preferred in interviews |
π Related Problemsβ
- LeetCode 160. Intersection of Two Linked Lists
- GFG: Intersection Point in Y Shaped Linked Lists
- LeetCode 141. Linked List Cycle
- LeetCode 21. Merge Two Sorted Lists
π¬