Intersection of Two Linked Lists (LeetCode 160): Solution and Explanation
Two singly linked lists may merge at some node and share every node after it. Given both heads, return the first shared node, or None if the lists never meet. The lists must keep their original structure.
Watch it run step by step
Try your own input and write the code →Intuition
The direct approach is to put every node of list A into a hash set, then walk list B and return the first node that is already in the set. Note that you compare node identity, not values, since two different nodes can hold the same number. That runs in O(m + n) time but needs O(m) memory, and the follow-up asks for constant space.
The real difficulty is that the lists can have different lengths before the merge point. If both had the same number of nodes before merging, you could walk them in lockstep and they would reach the shared node at the same moment. One fix is to count both lengths, advance the longer list by the difference, and then walk together. That works in constant space but needs extra passes and bookkeeping.
The switching trick equalizes the lengths automatically. Let A have x unique nodes, B have y unique nodes, and both share a tail of z nodes. Pointer a walks A and then jumps to the head of B; pointer b walks B and then jumps to the head of A. When a reaches the merge point the second time around, it has walked x + z + y steps, and b has walked y + z + x steps, which is the same. So they arrive together. If there is no shared tail, both pointers reach None after walking every node of both lists, and the loop ends with None.
Approach: Two pointers that switch lists
- Start
aatheadAandbatheadB. - Loop while
aandbare not the same node (identity comparison). - Advance
atoa.next, but ifais None, redirect it toheadBinstead. - Advance
btob.next, but ifbis None, redirect it toheadAinstead. - When the loop ends,
ais either the intersection node or None if the lists never merge. Returna.
Step-by-step example
A = [4, 1, 8, 4, 5], B = [5, 6, 1, 8, 4, 5], sharing the nodes from 8 onward
- Here A has two unique nodes (4, 1), B has three (5, 6, 1), and the shared tail is 8, 4, 5.
- After 5 steps,
ahas walked all of A and becomes None, whilebis on B's last node, 5. - Step 6 sends
ato B's head (5) and movesbto None. Step 7 movesato 6 and sendsbto A's head (4). - Step 8 moves
ato B's 1 andbto A's 1. These are different nodes even though the values match. - Step 9 moves both pointers to the node with value 8. They are now the same node, so the loop stops and returns 8.
Code: Python, Java, C++
1class Solution:
2 def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
3 a, b = headA, headB
4 while a != b:
5 a = headB if a is None else a.next
6 b = headA if b is None else b.next
7 return a1public class Solution {
2 public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
3 ListNode a = headA, b = headB;
4 while (a != b) {
5 a = (a == null) ? headB : a.next;
6 b = (b == null) ? headA : b.next;
7 }
8 return a;
9 }
10}1class Solution {
2public:
3 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
4 ListNode *a = headA, *b = headB;
5 while (a != b) {
6 a = (a == nullptr) ? headB : a->next;
7 b = (b == nullptr) ? headA : b->next;
8 }
9 return a;
10 }
11};Time and space complexity
O(m + n)
Each pointer walks at most its own list, one None, and the other list before the two meet or both become None, so there are at most m + n + 1 iterations.
O(1)
Only two pointers are used and neither list is modified.
Other approaches
Hash set of nodes from list A (time O(m + n), space O(m))
Store every node of A in a set, then return the first node of B found in the set. It is easy to reason about and fine when memory is not a concern.
Length difference alignment (time O(m + n), space O(1))
Count both lengths, advance the longer list's pointer by the difference, then walk both together until they match. It uses constant space like the switching trick and some people find it easier to justify in an interview.
Common mistakes
- Comparing node values instead of node identity. Both lists in the example contain a 1 that is not shared, so value comparison returns the wrong node.
- Switching to the other head when
a.nextis None instead of whenais None. Skipping the None step means both pointers never visit None together, so lists with no intersection loop forever. - Redirecting
ato its own head instead of the other list's head. The trick only works because each pointer walks both lists. - Modifying the lists, for example by temporarily linking the tail of A to B to turn this into a cycle problem, and forgetting to restore them.
Frequently asked questions
Why do the two pointers meet at the intersection?
After switching lists, both pointers have walked the unique part of A, the unique part of B, and the shared tail, just in different orders. Equal distances mean they reach the first shared node on the same step.
What if the two lists do not intersect?
Both pointers walk m + n nodes and then reach None at the same time. Since None equals None, the loop ends and the function returns None.
Can you solve Intersection of Two Linked Lists in O(1) space?
Yes. Both the head-switching pointers and the length-alignment method use only a few variables and do not change the lists.