Fast & Slow Pointers Pattern (Tortoise and Hare)
The Fast & Slow Pointers technique, also known as the "Tortoise and Hare" algorithm, uses two pointers that move through a data structure at different speeds. This pattern is particularly useful for detecting cycles and finding middle elements.
When to Use This Pattern
- Detecting cycles in linked lists
- Finding the middle element of a linked list
- Finding the k-th element from the end
- Detecting cycles in arrays (using indices as pointers)
- Problems involving "Happy Number" or similar cycle detection
Key Concepts
The pattern uses two pointers:
- Slow pointer: Moves one step at a time
- Fast pointer: Moves two steps at a time (or faster)
If there's a cycle, the fast pointer will eventually catch up to the slow pointer. If there's no cycle, the fast pointer will reach the end first.
Visual Representation
Fast & Slow Pointers - Cycle Detection (Floyd's Algorithm)
Floyd's Cycle Detection: Fast pointer moves 2 steps while slow moves 1 step. In a cycle, fast will eventually catch up to slow, proving a cycle exists. Time: O(n), Space: O(1).
Cycle Detection
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True # Cycle detected
return False # No cycle