Skip to content
StackDecode
Array techniquesAnimated

Fast and Slow Pointer Technique

Two pointers moving at different speeds reveal cycles and midpoints.

Time

O(n)

Extra space

O(1)

Use it for

Cycle detection, finding the middle.

How it works

  1. Treat the array as a map: index i points to a[i]. Because a value repeats, two indexes point to the same place, creating a cycle.
  2. Move a slow pointer one step (slow = a[slow]) and a fast pointer two steps (fast = a[a[fast]]) until they meet inside the cycle.
  3. Restart one pointer at index 0 and move both one step at a time. They meet exactly at the cycle entrance, which is the duplicate value.
  4. O(n) time and O(1) memory, without modifying the array.

Watch it run

Loading animation…