Intersection of Two Linked Lists
Given the heads of two singly linked lists headAheadBnull
Example 1
Output: Node with value 8
Explanation: The intersected node has value 8. Lists share the suffix [8, 4, 5].
Example 2
Output: null
Explanation: The two lists do not intersect.
Solution Approach - Two Pointer Trick
The elegant O(1) space approach uses two pointers pApB
Why does this work? If list A has length abca + (b - c)b + (a - c)
- Initialize
andpA = headA .pB = headB - Advance each pointer one step. When a pointer reaches null, redirect it to the other list's head.
- If both pointers are equal (even if both null), return that node (or null if no intersection).
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public class IntersectionOfTwoLinkedLists {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode pA = headA;
ListNode pB = headB;
// Both pointers traverse a + b total nodes, so they meet at intersection
while (pA != pB) {
pA = (pA == null) ? headB : pA.next;
pB = (pB == null) ? headA : pB.next;
}
return pA; // either the intersection node or null
}
}
Complexity Analysis:
Time complexity: O(m + n) where m and n are the lengths of the two lists. Each pointer traverses at most m + n nodes.
Space complexity: O(1) as only two pointer variables are used.