Fast & Slow Pointers: Floyd's Cycle Detection & Middle Node Finding
Fast & Slow Pointers: Floyd's Cycle Detection & Middle Node Finding
The Fast and Slow Pointer Technique (also celebrated as Floyd's Tortoise and Hare Algorithm) is a two-pointer pattern where two pointers traverse a sequence at different speeds. It is the gold standard for detecting loops in linked lists, locating the middle node, and finding the entrance of a cycle in $O(n)$ time and $O(1)$ space.
1. Real-World Analogy: Runners on a Track
Imagine two runners, a Tortoise and a Hare, running on an Olympic running track:
- Straight Road (No Cycle): The fast runner (Hare) reaches the finish line and stops. They never cross paths again.
- Circular Track (Cycle Exists): Because the track loops, the faster runner running at 2 meters/sec will inevitably lap and collide with the slower runner running at 1 meter/sec!
2. Problem 1: Find the Middle Node of a Linked List in a Single Pass
In an array, finding the middle is trivial: arr[n // 2]. In a linked list where the total length $n$ is unknown:
- Initialize
slow = headandfast = head. - Move
slowby 1 step (slow = slow.next). - Move
fastby 2 steps (fast = fast.next.next). - When
fastreaches the end (fast is Noneorfast.next is None),slowis precisely at the middle node!
Python 3:
3. Problem 2: Floyd's Cycle Detection Algorithm
Detect if a linked list contains a cycle:
Modern JavaScript / TypeScript:
4. Problem 3: Finding the Exact Cycle Entry Node (Floyd's Phase 2)
Once slow and fast collide at point $C$, how do you find the exact node where the cycle began?
- 1Keep
slowat the collision meeting point. - 2Reset
fastback to theheadof the linked list. - 3Advance both
slowandfastat the same speed of 1 step per tick. - 4The exact node where they collide again is the Entry Node of the Cycle!
5. Trace Table: Fast & Slow Middle Finding on 1 -> 2 -> 3 -> 4 -> 5 -> NULL
| Step | slow Node | fast Node | fast.next | Loop Condition (fast && fast.next) |
|---|---|---|---|---|
| Start | 1 | 1 | 2 | True |
| 1 | 2 | 3 | 4 | True |
| 2 | 3 (Middle!) | 5 | NULL | False (Loop terminates) |
Result: slow stops at Node 3 in exactly $\frac{n}{2}$ steps without needing a counter or second pass!
Multiple Choice Questions
Stacks: LIFO Operations, Array/List Implementations & Bracket Matching
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.