Data Structures19 sections · 729 units
Open in Course

Fast-Slow Pointer Technique

Two pointers, different speeds

The fast-slow pointer technique (also called Floyd's algorithm) uses two pointers moving at different speeds.

slow = head
fast = head
while fast != null and fast.next != null:
    slow = slow.next
    fast = fast.next.next

When fast reaches the end, slow is at the middle. Why? Fast moves twice as fast, so it covers twice the distance in the same number of steps.

This technique solves three categories of problems:

1.1. Finding the middle of a list

2.2. Detecting cycles

3.3. Finding the start of a cycle

All in O(n)O(n) time and O(1)O(1) space.