Linked List Cycle II
Problem (restated)
Return the node where the cycle begins, or null.
Intuition
After meet, restart one pointer at head; same pace meets at entrance.
Approaches
Floyd's cycle entry
UnverifiedIdea. Detect cycle with fast/slow; then head and meet walk until equal.
Walkthrough. Cycle starting at node 2: second phase returns that node.
Trade-offs. Hash set of seen nodes is O(n) 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 detectCycle(head: ListNode | null): ListNode | null {
if (!head?.next) return null;
let slow: ListNode | null = head, fast: ListNode | null = head;
while (fast?.next) {
slow = slow!.next; fast = fast.next.next;
if (slow === fast) {
let p: ListNode | null = head;
while (p !== slow) { p = p!.next; slow = slow!.next; }
return p;
}
}
return null;
}
export function detectCycle(head: ListNode | null): ListNode | null {
if (!head?.next) return null;
let slow: ListNode | null = head, fast: ListNode | null = head;
while (fast?.next) {
slow = slow!.next; fast = fast.next.next;
if (slow === fast) {
let p: ListNode | null = head;
while (p !== slow) { p = p!.next; slow = slow!.next; }
return p;
}
}
return null;
}
Template connection
Phase one is the same meeting as cycle detection. Then one pointer starts at the head and one at the meeting point, one step each. They meet at the cycle entrance. That entrance is the head only when the cycle starts there.
Reflection
- Finding a cycle is not enough; you need the entry. Why does one pointer reset to the head while both then move +1?
- No cycle returns null. If the cycle is the whole list, is the entry the head?
- State the relation between the meeting point and the entry in one sentence.