Fast and Slow Pointers
Fast and Slow Pointers
The fast and slow pointer technique (also called Floyd's tortoise and hare) uses two pointers moving at different speeds through a sequence. The speed difference creates useful properties: the slow pointer lands at the middle when fast reaches the end, and if there's a cycle, the two pointers will eventually meet.
Core Idea
- Slow pointer moves 1 step per iteration
- Fast pointer moves 2 steps per iteration
When fast reaches the end of the array (or list), slow is exactly at the midpoint. This happens because fast covers twice the distance in the same number of iterations.
Code Snippet — Finding the Middle
def find_middle_element(numbers: list[int]) -> int:
"""Find the middle element using two pointers at different speeds."""
slow_index = 0
fast_index = 0
while fast_index < len(numbers) - 1:
slow_index += 1 # slow moves 1 step
fast_index += 2 # fast moves 2 steps
# Prevent fast from going out of bounds
if fast_index >= len(numbers):
break
return numbers[slow_index]
Code Snippet — Cycle Detection (Floyd's Algorithm)
For linked-list-style problems where you follow "next" pointers:
def has_cycle(next_pointers: list[int], start: int) -> bool:
"""Detect if following next_pointers from start leads to a cycle.
next_pointers[node] gives the next node, -1 means end."""
slow_position = start
fast_position = start
while True:
# Move slow one step
slow_position = next_pointers[slow_position]
if slow_position == -1:
return False # reached end, no cycle
# Move fast two steps
fast_position = next_pointers[fast_position]
if fast_position == -1:
return False
fast_position = next_pointers[fast_position]
if fast_position == -1:
return False
# If they meet, there's a cycle
if slow_position == fast_position:
return True
Why This Works
For midpoint finding: After k iterations, slow is at position k and fast is at position 2k. When fast hits position n (the end), slow is at n/2 (the middle).
For cycle detection: If there's a cycle of length C, fast gains 1 position on slow per iteration. After at most C iterations inside the cycle, fast laps slow and they collide.
Applications
- Find middle of linked list — one pass, O(1) space
- Detect cycles — in linked lists, sequences, or function iteration
- Find cycle start — after detection, reset one pointer to start and move both at speed 1
- Check if number is happy — repeated digit-square-sum either cycles or reaches 1
- Palindrome linked list — find middle, reverse second half, compare
Time and Space
- Time: O(n) — each pointer traverses at most n elements
- Space: O(1) — only two pointer variables, no extra data structures
This is the key advantage over alternatives like using a hash set for cycle detection (which needs O(n) space).