17. Linked List Cycle Detection (Floyd's Algorithm)
Given head, the head of a linked list, determine if the linked list has a cycle in it.
How It Works & Algorithmic Design
Solves using Floyd's Tortoise and Hare Cycle Finding Algorithm:
- Pointers: Initialize
slow = headandfast = head. - Traversal: Advance
slowby 1 step (slow = slow.next) andfastby 2 steps (fast = fast.next.next). - Meeting Point: If a cycle exists, the fast pointer will eventually catch up and equal the slow pointer (
slow === fast$\to$ returntrue). - Termination: If
fast === nullorfast.next === null, a list tail was reached without a cycle $\to$ returnfalse.
Why This Approach Works Best
Detects loops without requiring $O(n)$ extra memory hash sets, running in $O(n)$ time complexity and true $O(1)$ space.
Example Walkthrough
Input:
3 -> 2 -> 0 -> -4 (points back to 2)Linked list with cycle.
Floyd's Trace:
Slow steps by 1, Fast steps by 2 -> Fast overlaps Slow inside loop.Pointers meet inside the loop.
Output:
trueCycle detected.
Answer: Floyd's Cycle Detection implementation
function hasCycle(head) {
let slow = head, fast = head;
while (fast !== null && fast.next !== null) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}💡 Use fast and slow pointers to detect cyclic references in linear time.
Key Takeaways
- Fast pointer moves at double speed ($2x$).
- If a cycle exists, fast pointer reduces distance by 1 node per iteration until meeting slow pointer.
- Runs in $O(n)$ time using $O(1)$ auxiliary space.