Introduction
Intersection of Two Linked Lists means finding the common node where both linked lists merge.
The task is to:
- detect common node
- return intersection point
- compare node references
Example:
List A:
1 -> 2 -> 8 -> 9
List B:
3 -> 8 -> 9
Output:8
Explanation:
Both linked lists
share nodes:
8 -> 9
Intersection starts at node 8.
This problem is one of the most important applications of:
Two Pointer Technique Constraints
0 <= Number of Nodes <= 10^5Approach 1 : Brute Force (Using Nested Traversal)
Explanations:
Explanation:
The idea is:
- compare every node of first list
- traverse second list fully
- find matching reference node
Steps:
- Pick node from first list.
- Traverse second list.
- Compare node addresses.
- Return matching node.
This approach works but:
- takes extra time
So Two Pointer solution is preferred.
Dry Run
List A:1 -> 2 -> 8 -> 9
List B:
3 -> 8 -> 9
Compare:
1 with all nodes
Compare:
2 with all nodes
Compare:
8 with 8
Intersection found.
Practice :
Complexity Analysis :
Time Complexity:- O(n × m)
Explanation :
Both linked lists are compared repeatedly.
Space Complexity:- O(1)
Explanation :No extra space is used.
Approach 2 : Optimal Solution(Using Two Pointers)
Explanations:
Explanation:
This is the most optimized and interview-preferred solution.
The idea is:
- traverse both lists
- switch heads after reaching end
- both pointers travel equal distance
If intersection exists:
- pointers meet there
Dry Run
List A:1 -> 2 -> 8 -> 9
List B:
3 -> 8 -> 9
Pointer A traverses:
A + B
Pointer B traverses:
B + A
Both pointers meet: at node 8
Practice :