DSA Tracker

Visualize

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

3
[0]
2
[1]
0
[2]
-4
[3]

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

Every step in words

Show all 14 steps
  1. 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).
  2. while condition check: fast!==null && fast.next!==null. Both valid (fast at idx0, next at idx1). Enter loop body.
  3. slow = slow.next advances to index 1 (value 2). Slow moves 1 step forward.
  4. fast = fast.next.next: first step to index 1 (value 2), then second step to index 2 (value 0). Fast moves 2 steps total.
  5. Check slow===fast? idx1 !== idx2, no cycle found yet. Continue loop.
  6. Second iteration: while condition check. fast at idx2, fast.next=idx3 (valid). Enter loop body.
  7. slow = slow.next advances to index 2 (value 0). Slow moves 1 step to index 2.
  8. fast = fast.next.next: from idx2, next=idx3 (value -4), next.next=idx1 (wrap cycle, value 2). Fast moves 2 steps to index 1.
  9. Check slow===fast? idx2 !== idx1, no cycle found. Continue loop.
  10. Third iteration: while condition check. fast at idx1, fast.next=idx2 (valid). Enter loop body.
  11. slow = slow.next advances to index 3 (value -4). Slow moves 1 step to index 3.
  12. fast = fast.next.next: from idx1, next=idx2 (value 0), next.next=idx3 (value -4). Fast moves 2 steps to index 3.
  13. Check slow===fast? idx3 === idx3 — they meet at index 3 (value -4) inside the cycle! Return true, cycle detected.
  14. 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.