← PatternsLinked List → Fast / Slow Pointers🐢🐇 Floyd's Cycle
🐢🐇
Fast / Slow Pointers — Floyd's Cycle Detection
Two pointers at different speeds — slow moves 1 step, fast moves 2 steps — to detect cycles, find midpoints, and locate cycle entry nodes in O(1) space.
Detect cycles in implicit sequences (Happy Number, Duplicate)
Need O(1) space — cannot use a HashSet for visited nodes
Check if a linked list is a palindrome (find mid + reverse)
💡 Key insight: if a cycle exists, fast will eventually "lap" slow and they meet inside the cycle. The meeting point math guarantees: resetting slow to head and moving both 1 step at a time leads them to the cycle start.
⚡ Complexity
Time
O(n)
Space
O(1)
Phase 1 (detect): at most O(λ + μ) steps where λ = cycle length, μ = tail length. Phase 2 (find start): at most O(μ) more steps. Total = O(n). Only two pointer variables — no extra data structures.
Math Proof Sketch
meet point distance from start = μ (tail)
∴ slow(reset to head) and fast both
reach cycle entry after μ more steps ✓
Live Animation · Fast & Slow Pointers · LC #141
Problem
Given linked list 1→2→3→4→5→(tail back to node 3), detect whether a cycle exists and find where it begins (LC #141). Fast pointer moves 2 steps, slow moves 1 — they meet inside the cycle. Reset slow to head, advance both 1 step at a time to find the entry node.
Input: [1,2,3,4,5], tail connects to node 3 · Answer: cycle detected, entry = node 3 · middle of [1,2,3,4,5] = node 3 (LC #876)