Intersection of Linked Lists
The Intersection of Linked Lists problem asks us to find the first common node shared by two singly linked lists. The challenge is to identify the same node in memory, even when the two lists have different starting points and different lengths.
1. What is Intersection of Linked Lists?
Two linked lists intersect when they share one or more actual nodes. Once the lists meet at a common node, their remaining nodes are shared.
Example
List A: 10 -> 20
\
30 -> 40 -> 50 -> nullptr
/
List B: 15 -> 25
Both lists share the nodes containing 30, 40, and 50. Therefore, the first intersection node contains 30.
2. Understanding Node Identity
Consider two nodes that both store the value 100:
List A: [100] -> [200]
List B: [100] -> [300]
If these are separate node objects stored at different memory addresses, the lists do not intersect.
However, if both lists point to the exact same node object, an intersection exists.
3. Approach 1: Using Two Pointers
The two-pointer approach is one of the most efficient ways to solve this problem. We use two pointers:
- Pointer A: Starts from the head of the first list.
- Pointer B: Starts from the head of the second list.
Follow these steps:
- Initialize pointer A at headA and pointer B at headB.
- Move both pointers one node forward in each iteration.
- When pointer A reaches nullptr, move it to headB.
- When pointer B reaches nullptr, move it to headA.
- Continue until both pointers meet.
- The meeting node is the intersection node, or nullptr if no intersection exists.
4. C++ Implementation Using Two Pointers
struct ListNode {
int val;
ListNode* next;
ListNode(int x) {
val = x;
next = nullptr;
}
};
ListNode* getIntersectionNode(
ListNode* headA,
ListNode* headB
) {
ListNode* a = headA;
ListNode* b = headB;
while (a != b) {
if (a == nullptr) {
a = headB;
} else {
a = a->next;
}
if (b == nullptr) {
b = headA;
} else {
b = b->next;
}
}
return a;
}
Explanation
- Both pointers initially start at their respective list heads.
- Each pointer moves one node at a time.
- When a pointer reaches the end, it starts from the other list's head.
- If an intersection exists, both pointers eventually reach the same node.
- If no intersection exists, both pointers eventually become nullptr together.
5. Dry Run of the Two-Pointer Approach
Consider the following linked lists:
List A: 4 -> 1
\
8 -> 4 -> 5
/
List B: 5 -> 6
Both lists share the nodes 8, 4, and 5. The first common node is 8.
Pointer movement:
| Iteration | Pointer A | Pointer B |
|---|---|---|
| 1 | 4 | 5 |
| 2 | 1 | 6 |
| 3 | 8 | nullptr |
| 4 | 4 | 4 (headA) |
| 5 | 5 | 1 |
| 6 | nullptr | 8 |
| 7 | 5 (headB) | 4 |
| 8 | 6 | 5 |
| 9 | 8 | nullptr |
| 10 | 4 | 5 (headA) |
| 11 | 5 | 1 |
| 12 | nullptr | 8 |
| 13 | 5 (headB) | 4 |
| 14 | 6 | 5 |
| 15 | 8 | nullptr |
| 16 | 4 | 5 (headA) |
| 17 | 5 | 1 |
| 18 | nullptr | 8 |
| 19 | 5 (headB) | 4 |
| 20 | 6 | 5 |
6. Approach 2: Using Length Difference
Another approach is to calculate the lengths of both linked lists. The longer list is then advanced by the difference in their lengths. After that, both pointers move together until they meet.
Steps
- Calculate the length of the first linked list.
- Calculate the length of the second linked list.
- Find the difference between the two lengths.
- Move the pointer of the longer list forward by that difference.
- Move both pointers together until they meet or reach nullptr.
- Return the common node, if one exists.
C++ Implementation
int getLength(ListNode* head) {
int length = 0;
while (head != nullptr) {
length++;
head = head->next;
}
return length;
}
ListNode* getIntersectionUsingLength(
ListNode* headA,
ListNode* headB
) {
int lenA = getLength(headA);
int lenB = getLength(headB);
while (lenA > lenB) {
headA = headA->next;
lenA--;
}
while (lenB > lenA) {
headB = headB->next;
lenB--;
}
while (headA != headB) {
headA = headA->next;
headB = headB->next;
}
return headA;
}
7. Complete C++ Program
This program creates two linked lists that share a common tail. It then finds the first common node using the two-pointer approach.
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) {
val = x;
next = nullptr;
}
};
ListNode* getIntersectionNode(
ListNode* headA,
ListNode* headB
) {
ListNode* a = headA;
ListNode* b = headB;
while (a != b) {
a = (a == nullptr) ? headB : a->next;
b = (b == nullptr) ? headA : b->next;
}
return a;
}
void display(ListNode* head) {
while (head != nullptr) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
void deleteList(ListNode* head) {
while (head != nullptr) {
ListNode* temp = head;
head = head->next;
delete temp;
}
}
int main() {
// Create the shared part only once.
ListNode* common = new ListNode(30);
common->next = new ListNode(40);
common->next->next = new ListNode(50);
// First list: 10 -> 20 -> 30 -> 40 -> 50
ListNode* headA = new ListNode(10);
headA->next = new ListNode(20);
headA->next->next = common;
// Second list: 15 -> 25 -> 30 -> 40 -> 50
ListNode* headB = new ListNode(15);
headB->next = new ListNode(25);
headB->next->next = common;
cout << "List A: ";
display(headA);
cout << "List B: ";
display(headB);
ListNode* intersection =
getIntersectionNode(headA, headB);
if (intersection != nullptr) {
cout << "Intersection found at node: "
<< intersection->val << endl;
} else {
cout << "No intersection found" << endl;
}
// Delete the separate prefix of list B first.
delete headB->next;
delete headB;
// Delete the shared nodes and list A prefix once.
deleteList(headA);
return 0;
}
Output
List A: 10 20 30 40 50
List B: 15 25 30 40 50
Intersection found at node: 30
8. What if There is No Intersection?
If the two lists do not share any node, the two-pointer algorithm eventually makes both pointers nullptr.
Example
List A: 1 -> 2 -> 3 -> nullptr
List B: 4 -> 5 -> 6 -> nullptr
No intersection found
9. Time and Space Complexity
| Approach | Time Complexity | Auxiliary Space |
|---|---|---|
| Two Pointers | O(n + m) | O(1) |
| Length Difference | O(n + m) | O(1) |
| Hash Set | O(n + m) expected | O(n) |
Here, n and m represent the lengths of the two linked lists. The two-pointer approach is efficient because it traverses each list at most twice and uses only a fixed number of pointers.
10. Important Edge Cases
- Both linked lists are empty.
- Only the first linked list is empty.
- Only the second linked list is empty.
- Both lists intersect at their head nodes.
- Both lists intersect at their last node.
- Both lists have different lengths.
- The two lists do not intersect.
- Both heads point to the same linked list.
11. Common Mistakes
- Comparing node values instead of node addresses.
- Forgetting to switch a pointer to the other list's head.
- Using an incorrect loop condition.
- Assuming both linked lists have equal lengths.
- Not handling empty linked lists.
- Creating separate nodes with equal values and assuming they intersect.
- Deleting shared nodes more than once in test programs.
12. Applications
- Detecting shared structures in linked data.
- Identifying common nodes in memory-based data structures.
- Understanding pointer relationships and memory addresses.
- Solving linked-list problems in coding interviews.
- Analyzing shared paths in pointer-based structures.
13. Interview Questions
- What does intersection mean in linked lists?
- Why should we compare node addresses instead of values?
- How does the two-pointer approach work?
- Why do we switch pointers to the opposite list's head?
- What is the time complexity of the two-pointer solution?
- Can we find intersection without using extra memory?
- How does the length-difference approach work?
- What happens when two lists do not intersect?
- Can two lists with different lengths intersect?
- How would you handle two lists that share their entire structure?
14. Practice Problems
- Find the intersection node of two singly linked lists.
- Solve the intersection problem using two pointers.
- Solve the problem using the length-difference approach.
- Find whether two linked lists intersect or not.
- Find the intersection when both lists have different lengths.
- Find the first common node when both lists share a common tail.
- Explain why equal node values do not necessarily indicate an intersection.
15. Summary
- Two linked lists intersect when they share the same physical node.
- Equal values alone do not indicate an intersection.
- The two-pointer approach switches each pointer to the other list's head.
- The first common node is returned when both pointers meet.
- If no intersection exists, both pointers eventually become nullptr.
- The optimal two-pointer solution takes O(n + m) time and O(1) auxiliary space.