Cycle Detection
Picture two runners on a track: if it loops, the faster one (2 steps per tick) gains exactly one step on the slower one (1 step per tick) every tick, so the gap between them shrinks by one each time and must eventually hit zero — they're forced to collide somewhere inside the cycle. If the track doesn't loop, that collision never gets a chance to happen — the fast pointer just runs off the end into null first. Floyd's algorithm races a slow and a fast pointer at those two speeds and watches whether they meet or fast escapes to null.
Details
Animated on: Detect if a cycle exists in linked list 3->2->0->-4 where tail connects to index 1 (value 2)
Problem:Linked List CycleEasy
Pattern:Fast and Slow Pointers
Linked List
step 1 / 14
Initialize slow and fast pointers both at head (index 0, value 3). Array [3, 2, 0, -4] with next pointers: idx0→idx1, idx1→idx2, idx2→idx3, idx3→idx1 (cycle back).
- slow=0· arr[0] = 3
- fast=0· arr[0] = 3
1FUNCTION hasCycle(head):2 slow = head; fast = head3 WHILE fast is not empty and the node after fast is not empty:4 move slow one node forward5 move fast two nodes forward6 IF slow and fast are the same node: RETURN true7 END WHILE8 RETURN false9END FUNCTION
← / → step · space play · Home restart
Every step in words
Show all 14 steps
- Initialize slow and fast pointers both at head (index 0, value 3). Array [3, 2, 0, -4] with next pointers: idx0→idx1, idx1→idx2, idx2→idx3, idx3→idx1 (cycle back).
- while condition check: fast!==null && fast.next!==null. Both valid (fast at idx0, next at idx1). Enter loop body.
- slow = slow.next advances to index 1 (value 2). Slow moves 1 step forward.
- fast = fast.next.next: first step to index 1 (value 2), then second step to index 2 (value 0). Fast moves 2 steps total.
- Check slow===fast? idx1 !== idx2, no cycle found yet. Continue loop.
- Second iteration: while condition check. fast at idx2, fast.next=idx3 (valid). Enter loop body.
- slow = slow.next advances to index 2 (value 0). Slow moves 1 step to index 2.
- fast = fast.next.next: from idx2, next=idx3 (value -4), next.next=idx1 (wrap cycle, value 2). Fast moves 2 steps to index 1.
- Check slow===fast? idx2 !== idx1, no cycle found. Continue loop.
- Third iteration: while condition check. fast at idx1, fast.next=idx2 (valid). Enter loop body.
- slow = slow.next advances to index 3 (value -4). Slow moves 1 step to index 3.
- fast = fast.next.next: from idx1, next=idx2 (value 0), next.next=idx3 (value -4). Fast moves 2 steps to index 3.
- Check slow===fast? idx3 === idx3 — they meet at index 3 (value -4) inside the cycle! Return true, cycle detected.
- Return true: cycle confirmed. Slow and fast met at index 3 (value -4) where tail connects back to index 1 (value 2).
Now solve it yourself
Watching is the first half. The second is writing it without the animation.