Detect Cycle Visualizer
Linked ListMediumTwo pointers

Detect Cycle Visualizer

Slow moves one step, fast moves two. If they ever land on the same node, there is a loop.

In easy words

On a circular track a faster runner laps a slower one. If the list is a line, the fast runner hits the end.

Where this shows up

Cycle detection in graphs of nodes, hashmap memory leaks, and finding the loop start (Floyd phase 2).

Key facts

  • Floyd - tortoise and hare, O(1) extra memory.
  • Hash set - store seen nodes, O(n) memory.
  • Meet - same node reference, not equal values.
  • No cycle - fast becomes None.

What to remember

  • Time - O(n).
  • Space - O(1) for Floyd.
  • Single node self-loop - they meet immediately after one move.
  • Entry point - after meet, reset one pointer to head and walk together.

Theory

If a cycle exists, the faster pointer eventually laps the slower one inside the loop. This proves a cycle without storing every visited node.

Problem Statement

Given head of a linked list, return true if there is a cycle.

Example: 1 → 2 → 3 → 4 back to 2 has a cycle. 1 → 2 → 3 → None does not.

Approach

  1. Floyd's tortoise and hare. Slow moves one node, fast moves two.
  2. If they ever point to the same node, a cycle exists: the faster runner lapped the slower one on a loop.
  3. If fast hits None, the list is a straight line — no cycle.
  4. Why it works: inside a loop the gap shrinks by one each step, so they must meet. Extra memory is O(1).

Visualization and algorithm execution

Ready

Example code

1slow = fast = head
2while fast and fast.next:
3slow = slow.next
4fast = fast.next.next
5if slow == fast:
6return True
7return False
Trace log

Step-by-step visualization

slow = tortoise, fast = hare
?
Output:

Example program

Python

1def hasCycle(head):
2slow = fast = head
3while fast and fast.next:
4slow = slow.next
5fast = fast.next.next
6if slow is fast: return True
7return False