Loading section...

Fast and Slow Pointers

Concepts: pyFastSlowPointers, pyFloydsCycle

The third sub-pattern: two pointers moving at different speeds. The slow pointer moves one step at a time. The fast pointer moves two steps. This is Floyd's cycle detection algorithm, also called the tortoise and hare. If there is a cycle, the fast pointer will eventually lap the slow pointer and they will meet. If there is no cycle, the fast pointer reaches the end. This pattern shows up in linked list problems and is good to know for phone screens. Detect a Cycle in a Linked List Why does this work? Imagine a circular track. If two runners start at the same point and one runs twice as fast, the fast runner will eventually lap the slow runner. The distance between them decreases by 1 each step (fast gains 1 step, but in a cycle, that means closing the gap). They are guaranteed to meet. Th