Fast & Slow Pointers

Two pointers walk the same sequence at different speeds. The gap between them finds cycles, the middle of a list and the k-th node from the end, all in O(1) extra space.

Overview

The idea

A linked list has no length field and no index. To learn something about its shape you have to walk it. The fast and slow pointer technique walks it once with two pointers: slow moves one node per step and fast moves two. What you learn comes from the gap between them.

That one gap answers four different questions about a list.

  • Is there a cycle? Fast either reaches the end, which means no cycle, or catches up with slow, which means there is one.
  • Where is the middle? When fast reaches the end, slow has covered half the distance.
  • Where is the k-th node from the end? Start fast k nodes ahead. When fast runs off the end, slow is on the k-th node from the end.
  • Where does the cycle start? After the pointers meet, walk one pointer from the head and one from the meeting point, at the same speed.

The cycle test is usually called Floyd's tortoise and hare. Knuth credited it to Robert W. Floyd, but it does not appear in Floyd's published work and may be folklore. The alternative is a set of visited nodes, which costs O(n) extra space. The two pointers cost O(1).

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio