Intersection of Two Linked Lists
Master this topic with zero to advance depth.
Intersection of Two Linked Lists
Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.
Visual Representation
List A: a1 -> a2
\
c1 -> c2 -> c3
/
List B: b1 -> b2 -> b3
Intersection at c1.Examples
Level I: Brute Force (Hashing)
Intuition
Traverse the first list and store all node addresses in a hash set. Then, traverse the second list and check if any node exists in the set.
Detailed Dry Run
List A: [A, B, C]. Set: {A, B, C}. List B: [D, E, B, C]. Search D (no), E (no), B (yes!). Intersection at B.
⚠️ Common Pitfalls & Tips
O(N) space is not ideal. Note that you must store node pointers/references, not just values.
Level II: Length Difference
Intuition
Calculate lengths of both lists. Move the pointer of the longer list forward by the difference. Then move both pointers together until they meet.
Visual Trace
A: 1 -> 2 -> 3 -> C1 (Len 4)
B: 4 -> C1 (Len 2)
Diff = 2. Advance pointer A by 2 steps.
Pointer A starts at 3, B starts at 4.
Move both: A=C1, B=C1. Match!Detailed Dry Run
A: [4,1,8,4,5], B: [5,6,1,8,4,5]. LenA=5, LenB=6. Diff=1. Move B forward by 1 (to 6). Both move together: (1,1), (8,8) -> Intersect at 8.
Level III: Optimal (Two Pointers)
Intuition
Use two pointers, pA and pB. Traverse both lists. When a pointer reaches the end, redirect it to the head of the other list. They will meet at the intersection point or both become null.
Detailed Dry Run
A: [1,2,c], B: [3,c].
- pA=1, pB=3.
- pA=2, pB=c.
- pA=c, pB=null->pA=1.
- pA=null->pB=3, pB=c. They meet after switched paths.
⚠️ Common Pitfalls & Tips
The pointers will meet even if there is no intersection (both will be null).
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.