Floyd's Linked List Cycle Finding
Given a linked list that may contain a cycle, detect the cycle and find its entry (node C where the loop begins).
Floyd’s cycle algorithm (tortoise and hare) does this in O(n) time and O(1) extra memory.
This lesson follows CP-Algorithms — Floyd’s cycle finding.
Related: Simulated Annealing (also uses a “ρ” / tortoise–hare idea in Pollard ρ — see Integer Factorization).
Phase 1 — Does a cycle exist?
slowandfastboth start athead.- Each step:
slow = slow.next,fast = fast.next.next. - If they ever point to the same node → cycle.
- If
fasthitsnull→ acyclic.
public boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
Fast covers twice the distance of slow; the gap grows by 1 each iteration. Once both are in a cycle of length L, they meet after a finite number of steps (the lead is a multiple of L mod L).
Phase 2 — Where does the cycle start?
After they meet at G inside the cycle:
- Reset
slow = head(leavefastatG). - Advance both one step at a time.
- Their next meeting point is
C, the cycle entry.
// slow, fast already meet inside the cycle
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow; // entry C
Why phase 2 works
Let:
a= steps from head toCb= steps fromCto first meetingGL= cycle length
At the first meeting:
slowDist = a + x L + b
fastDist = a + y L + b
fastDist = 2 · slowDist
⇒ a = (y − 2x) L − b
So walking a steps from head reaches C, and walking a steps from G (already b into the cycle) also wraps to C. Moving both one-by-one, they meet at the entry.
🧪 Tortoise & hare on an array “next” list
Check: Floyd cycle finding
Floyd cycle finding
1 / 4In phase 1, fast moves…
Pick an answer to see if you are right.
Practice drills
next is given as a list (-1 = null). Input: i. Print next[i] (or -1 if i < 0).
Practice problems
From CP-Algorithms / common LC mirrors:
- Linked List Cycle (Easy)
- Happy Number (Easy)
- Find the Duplicate Number (Medium)
- Linked List Cycle II (entry point)
Cheat sheet
| Phase | Action |
|---|---|
| 1 | slow +1, fast +2 until equal or null |
| Meet | Proves a cycle; node is some G in the loop |
| 2 | slow = head; both +1 until equal → entry C |
| Why | a ≡ −b (mod L) from fast = 2·slow |
| Cost | O(n) time, O(1) memory |