Floyd's Cycle Detection visualization

Tortoise moves 1 step, hare moves 2; if there is a loop they must meet inside it.

In a linked list with a cycle, the hare gains one node per step on the tortoise, so it eventually laps it. Without a cycle the hare simply reaches null.

To find the loop's entry, restart one pointer from the head and move both one step at a time — they meet at the cycle start. Edge cases: empty list, single node, self-loop.

Complexity

Time: best O(1), average O(n), worst O(n). Space: O(1). Difficulty: Intermediate.

Pseudocode

procedure hasCycle(head):
  slow ← head; fast ← head
  while fast ≠ null and fast.next ≠ null:
    slow ← slow.next; fast ← fast.next.next
    if slow = fast: break                   // cycle!
  if no meeting: return "no cycle"
  slow ← head
  while slow ≠ fast: slow ← slow.next; fast ← fast.next
  return slow                               // cycle entry

More techniques algorithms