Fast & Slow
Pointers
Floyd's tortoise and hare. Two pointers moving at different speeds through a sequence. One of the most elegant O(n) time, O(1) space techniques in computer science.
What is the fast and slow pointer technique?
Move two pointers through a linked list (or sequence) at different speeds, slow one step and fast two steps. If there's a cycle, fast eventually laps slow and they meet (Floyd's tortoise and hare). If there isn't, fast reaches the end. The same trick finds the middle of a list in one pass, because when fast reaches the end, slow is halfway.
function hasCycle(head) {
let slow = head, fast = head;
while (fast && fast.next) {
slow = slow.next; fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}
function middle(head) {
let slow = head, fast = head;
while (fast && fast.next) { slow = slow.next; fast = fast.next.next; }
return slow;
}Visualise the movement
// Acyclic list: fast reaches null first
Step-through trace
// Array state
// Pseudocode
The algorithm
Initialise both at head
Both slow and fast start at the head node. Fast will move twice as quickly, so when it reaches the end, slow is at the midpoint.
Cycle detection
1// Floyd cycle detection — O(n) time, O(1) space2function hasCycle(head):3 slow = head4 fast = head5 while fast and fast.next:6 slow = slow.next // move 1 step7 fast = fast.next.next // move 2 steps8 if slow == fast:9 return true // pointers met — cycle!10 return false // fast reached null — no cycle
Find middle node
1// Find middle node — O(n) time, O(1) space2function findMiddle(head):3 slow = head4 fast = head5 while fast and fast.next:6 slow = slow.next7 fast = fast.next.next8 return slow // when fast reaches end, slow = middle
Complexity
Linear time
Linear time
Linear time
Constant time
🎯 Quick Check
To find the middle of a linked list of 7 nodes using fast/slow pointers, how many steps does slow take?
Fast and Slow Pointers: summary
Key points
- O(n) time and O(1) space, versus O(n) space for a "seen" set.
- Also used for "happy number" and "find the duplicate number" problems.
Frequently asked questions
›Why do the fast and slow pointers meet in a cycle?
Inside the cycle, the fast pointer gains one step per move on the slow one, so the gap shrinks by one each time until it reaches zero.