Floyd's cycle detection uses two references: one moves a node at a time, and the other moves two. If a linked list loops, the faster reference eventually catches the slower one. No record of visited nodes is needed.
Detecting cycles without a set
A cycle exists when following next links returns to a node already visited. The task is to return true for a cycle and false for a list that ends at null. A Set can record the visited nodes:
function hasCycleNaive(head) {
let seen = new Set();
while (head !== null) {
if (seen.has(head)) {
return true; // Found a cycle!
}
seen.add(head);
head = head.next;
}
return false; // No cycle
}
The set based method is correct, but the set grows with the list, so the extra space is O(n).
Floyd's two pointer method
With two pointers, slow advances one node and fast advances two. If fast or fast.next reaches null, the list ends. Otherwise, the pointers eventually meet inside the cycle.
function hasCycle(head) {
if (head === null || head.next === null) {
return false; // An empty list or a null next link cannot form a cycle
}
let slow = head; // Moves 1 step at a time
let fast = head.next; // Moves 2 steps at a time
while (fast !== null && fast.next !== null) {
if (slow === fast) {
return true; // They met! There's a cycle
}
slow = slow.next; // Move slow pointer 1 step
fast = fast.next.next; // Move fast pointer 2 steps
}
return false; // Fast pointer hit null, no cycle
}
Once both pointers are inside a cycle, their positions repeat modulo the cycle length. The fast pointer gains one node on the slow pointer per iteration, so their relative distance eventually becomes zero. The null checks handle lists with no cycle before either pointer is dereferenced.
Complexity and applications
The same method applies to other sequences where each position has exactly one next position:
- Symlink verification: Detecting circular symbolic links in file systems
- Compiler dependency checking: Check for cycles when each module in the sequence has a single next dependency
The pointer loop takes O(n) time and O(1) extra space.
The single next step matters. For dependencies that branch to several nodes, this algorithm alone does not explore the whole graph.

Loading comments...