Pattern 03
Fast & Slow Pointers
Two pointers moving at different speeds reveal hidden structure.
When to use
Use for linked list cycles, finding the middle of a list, and repeated movement through a sequence at different speeds. If the problem involves a linked list and asks about position or loops, think here first.
Core intuition
One pointer moves 1 step. The other moves 2 steps. If there's a cycle, they'll eventually meet. If there's no cycle, the fast pointer hits null. When fast reaches the end, slow is near the middle.
Template
def has_cycle(head):
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
def find_middle(head):
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slowSuggested problems
Key takeaways
- ›One pointer moves 1 step, one moves 2 steps
- ›If they meet → there is a cycle
- ›If fast hits null → no cycle
- ›When fast ends, slow is at or near the middle
- ›Works on linked lists and on abstract number sequences
You'll see this when...
- ›Does this linked list have a cycle?
- ›Find the middle of a linked list
- ›Find the start of the cycle
- ›Is this number a happy number?
- ›Remove the nth node from the end