← Lessons

quiz vs the machine

Silver1120

Algorithms

The Fast and Slow Pointers

Two pointers at different speeds to find midpoints and loops in linked structures.

4 min read · intro · beat Silver to climb

Two speeds, one traversal

The fast and slow pattern, sometimes called the tortoise and hare, advances one pointer one step at a time and another two steps at a time through the same structure. The gap between them grows in a predictable way, which lets you measure positions without counting.

Finding the middle

To locate the middle of a linked list, start both pointers at the head. Each iteration the slow pointer moves once and the fast pointer moves twice. When the fast pointer reaches the end, the slow pointer sits at the midpoint, found in a single pass with no length precomputation.

Detecting a loop

If the structure contains a cycle, the fast pointer eventually laps the slow one and they collide. If there is no cycle, the fast pointer simply runs off the end. This collide or escape behavior is the heart of loop detection.

Key idea

Running two pointers at one and two steps per iteration lets a single traversal reveal the midpoint of a list, and a collision between them signals a cycle without any extra memory.

Check yourself

Answer to earn rating on the learn ladder.

1. When the fast pointer reaches the end of the list, where is the slow pointer?

2. How does the pattern signal that a linked list contains a cycle?