Visualize

Pattern visualizer

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. Animated on: Detect if a cycle exists in linked list 3->2->0->-4 where tail connects to index 1 (value 2).

Linked List

step 1 / 14
3
[0]
2
[1]
0
[2]
-4
[3]
line 2

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).

Pseudocode
1FUNCTION hasCycle(head):
2 slow = head; fast = head
3 WHILE fast is not empty and the node after fast is not empty:
4 move slow one node forward
5 move fast two nodes forward
6 IF slow and fast are the same node: RETURN true
7 END WHILE
8 RETURN false
9END FUNCTION

← / → step · space play · Home restart

Where to practice Linked List