Intersection of Two Linked Lists
Difficulty: Easy · Pattern: Linked List · LeetCode #160
Two singly linked lists may merge at some node and share all nodes after it. Return the node where they intersect (by reference, not value), or null. Lists have no cycles. Aim for O(1) extra memory.
The tests describe inputs as [intersectVal, listA, listB, skipA, skipB]: listA's first skipA nodes and listB's first skipB nodes are separate, and the rest are shared. The expected output shows the intersection node's value (or null).
Examples
A: 4 → 1 ↘
8 → 4 → 5
B: 5 → 6 → 1 ↗ → node 8
A: 2 → 6 → 4, B: 1 → 5 → nullHints
- A hash set of A's nodes works with O(n) memory.
- If both pointers walk A then B (and B then A), they travel the same total distance.
Approach
Pointer p walks A and then continues at B's head; q walks B and then continues at A's head. After at most lenA + lenB steps, they either meet at the intersection node (both have walked a + c + b steps, where c is the shared tail) or both become null at the same time (no intersection). O(m + n), O(1).
Complexity
Time: O(m + n). Space: O(1).
Python solution
def getIntersectionNode(headA, headB):
p, q = headA, headB
while p is not q:
p = p.next if p else headB
q = q.next if q else headA
return pJavaScript solution
function getIntersectionNode(headA, headB) {
let p = headA, q = headB;
while (p !== q) { p = p ? p.next : headB; q = q ? q.next : headA; }
return p;
}