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!
1Visualizing Floyd's Tortoise and Hare on a Circular Track:
2Slow: moves 1 step per tick (Tortoise 🐢)
3Fast: moves 2 steps per tick (Hare 🐇)
4If Fast meets Slow (Slow == Fast), a cycle is mathematically guaranteed to exist!
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 = head and fast = head.
Move slow by 1 step (slow = slow.next).
Move fast by 2 steps (fast = fast.next.next).
When fast reaches the end (fast is None or fast.next is None), slow is precisely at the middle node!
Python 3:
1deffind_middle_node(head: ListNode)-> ListNode:
2 slow = head
3 fast = head
4
5while fast isnotNoneand fast.nextisnotNone:
6 slow = slow.next# Moves 1 step
7 fast = fast.next.next# Moves 2 steps
8
9return slow # When fast hits the end, slow is at the middle!