Intersection of Two Linked Lists
Problem (restated)
Return the intersection node of two singly linked lists, or null.
Intuition
When a pointer ends, jump to the other list’s head. distances equalize at the intersection.
Approaches
Two-pointer switch heads
UnverifiedIdea. Advance a and b; null → switch head; stop when a == b.
Walkthrough. Shared tail of length c: both meet after a+c+b steps.
Trade-offs. Hash set of list A is simpler O(m) space.
Show helper code
export class ListNode {
val: number; next: ListNode | null;
constructor(val = 0, next: ListNode | null = null) { this.val = val; this.next = next; }
}
export class ListNode {
val: number; next: ListNode | null;
constructor(val = 0, next: ListNode | null = null) { this.val = val; this.next = next; }
}
export function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null {
if (!headA || !headB) return null;
let a: ListNode | null = headA, b: ListNode | null = headB;
while (a !== b) { a = a ? a.next : headB; b = b ? b.next : headA; }
return a;
}
export function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null {
if (!headA || !headB) return null;
let a: ListNode | null = headA, b: ListNode | null = headB;
while (a !== b) { a = a ? a.next : headB; b = b ? b.next : headA; }
return a;
}
Template connection
Each pointer walks its own list. At null it switches to the other head. The walks then have the same length, so they meet at the shared node. No intersection means both arrive at null together.
Reflection
- Switching each pointer onto the other list’s head lines the tails up. Why does that cancel the length difference?
- With no intersection both pointers land on null together. Is an early null return a false positive?
- Is node equality by reference or by value? Same value, different node.