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
Tested onlyTime O(m+n)Space O(1)
Idea. 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.
Solution
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 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;
}
Reflection
- Which cue made you pick this pattern in under 90 seconds?
- What input would break a wrong invariant?