AlgoTales · Roadmap

Fast/slow pointers

Advanced · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Fast and slow pointers walk the same chain at different speeds, one step versus two steps. If the chain loops back on itself the fast one eventually catches the slow one, and if it ends they never meet; it also lands in the middle when the fast one finishes.

Practical use cases

  • Web app: Circular task dependencies in a project tool. A project planner lets users say "task A waits for B, B waits for C". If someone makes C wait for A, the plan can never start. Walking the chain with a fast and a slow marker detects the loop quickly, so the app shows a "circular dependency" warning on save.
  • Web app: Redirect loop detector. A site-migration tool follows redirect rules (page A goes to B goes to C). If the rules circle back, browsers show "too many redirects". Fast and slow walkers spot the loop without storing every page visited. Admins see the exact rule that loops, instead of customers seeing a browser error.
  • Web app: Middle item of a linked list. A playlist or queue implemented as a linked list needs its middle song for a "split into two halves" button. When the fast pointer reaches the end, the slow pointer sits at the middle, with a single pass and no counting.
  • System: Corrupt linked lists and number generators. Memory-debugging tools find broken lists that loop forever, and the same chase trick finds the repeat in a random-number sequence. It needs only two variables, so it works even where memory is tight.

The story: The Tortoise and the Hare on the Ring Road

Grandpa Bhaskar loved telling the story of two cyclists on the ring road around the old fort. Raju rode slowly, one lap-marker at a time. Kabir rode fast, two markers at a time. "If the road is a ring," said Grandpa, "the fast one must come up behind the slow one and meet him. If the road is a straight line, the fast one just reaches the end and never meets anyone."

Mira turned this into a puzzle for school. "A box holds a number. Open box 0 and it says 3, so go to box 3. That one says 4, so go to box 4..." If you keep following the notes forever, you either reach a dead end or you go round in a loop. With numbers 1 to n packed into n+1 boxes, a repeated number guarantees a loop, and the loop starts at the repeated number.

The smell is in the words: "a cycle", "follow the next pointer", "find the middle", "without extra memory", "numbers 1..n with one extra". When a problem walks along links, send a slow and a fast walker. If they ever meet, there is a loop. A second small walk finds exactly where the loop begins.

This is fast/slow pointers, also known as Floyd's tortoise and hare. It uses no table of visited places, just two markers.

How to spot this problem, and where you need it

You follow links one after another (next item, next redirect, next dependency) and need to know whether the chain loops forever, or where its middle is, without extra memory.

Signs you need it

  • A loop that follows next pointers or parent ids sometimes never ends and freezes the page or script.
  • The problem says "detect a cycle", "find the middle", or "find where the loop begins" in a linked structure.
  • Storing every visited item in a set would work but you are asked to use almost no extra memory.

Where to use it in a project

  • Validating dependency, redirect or workflow rules before saving them to the database.
  • Splitting or inspecting a linked-list-based queue, playlist or history stack.
  • Detecting repeating states in a sequence generator or a state machine.

The solution

Start two pointers at the head. Each round, move the slow one one step and the fast one two steps. If the fast one reaches the end, there is no loop. If the fast one ever lands on the same item as the slow one, there is a loop. For the middle, stop when fast reaches the end: slow is in the middle. Only two variables are needed.

Payoff: Before: an endless loop that hangs the request. After: a clean error message after at most a few thousand steps, and no extra memory.

Explain it like I am 8

Two kids run round a circular track. One runs at normal speed, the other twice as fast. On a circle the fast kid catches the slow kid, always. On a straight path she just reaches the end. So if they meet, you know the path is a circle.

How it works, step by step

  1. Clues: "cycle", "loop", "middle of a list", "follow pointers", "O(1) memory". Think fast and slow.
  2. Start both walkers at the same place. Each round: slow takes 1 step, fast takes 2 steps.
  3. If fast falls off the end (null), there is no loop. For the middle of a list, when fast reaches the end slow is at the middle.
  4. If they land on the same spot, there is a loop.
  5. To find the loop entrance: move slow back to the start, then move both one step at a time. Their next meeting spot is the entrance (here, the duplicate number).

The code in four languages

PHP

<?php
// Find the Duplicate Number: array of n+1 numbers in 1..n, one repeats.
// Treat nums[i] as "the next box after i" and find where the trail loops.
function findDuplicate(array $nums): int {
    $slow = 0;
    $fast = 0;
    do {
        $slow = $nums[$slow];            // one hop
        $fast = $nums[$nums[$fast]];     // two hops
    } while ($slow !== $fast);           // met inside the loop

    $slow = 0;                           // restart slow from the beginning
    while ($slow !== $fast) {
        $slow = $nums[$slow];            // both go one hop now
        $fast = $nums[$fast];
    }
    return $slow;                        // the loop entrance is the duplicate
}
echo findDuplicate([3, 1, 3, 4, 2]);     // 3

JavaScript

// Find the Duplicate Number: array of n+1 numbers in 1..n, one repeats.
// Treat nums[i] as "the next box after i" and find where the trail loops.
function findDuplicate(nums) {
  let slow = 0;
  let fast = 0;
  do {
    slow = nums[slow];             // one hop
    fast = nums[nums[fast]];       // two hops
  } while (slow !== fast);         // met inside the loop

  slow = 0;                        // restart slow from the beginning
  while (slow !== fast) {
    slow = nums[slow];             // both go one hop now
    fast = nums[fast];
  }
  return slow;                     // the loop entrance is the duplicate
}
console.log(findDuplicate([3, 1, 3, 4, 2]));   // 3

Java

public class Main {
    // Find the Duplicate Number: array of n+1 numbers in 1..n, one repeats.
    // Treat nums[i] as "the next box after i" and find where the trail loops.
    static int findDuplicate(int[] nums) {
        int slow = 0;
        int fast = 0;
        do {
            slow = nums[slow];             // one hop
            fast = nums[nums[fast]];       // two hops
        } while (slow != fast);            // met inside the loop

        slow = 0;                          // restart slow from the beginning
        while (slow != fast) {
            slow = nums[slow];             // both go one hop now
            fast = nums[fast];
        }
        return slow;                       // the loop entrance is the duplicate
    }

    public static void main(String[] args) {
        System.out.println(findDuplicate(new int[]{3, 1, 3, 4, 2}));   // 3
    }
}

Go

package main

import "fmt"

// findDuplicate: array of n+1 numbers in 1..n, one repeats.
// Treat nums[i] as "the next box after i" and find where the trail loops.
func findDuplicate(nums []int) int {
	slow, fast := 0, 0
	for {
		slow = nums[slow]       // one hop
		fast = nums[nums[fast]] // two hops
		if slow == fast {       // met inside the loop
			break
		}
	}

	slow = 0 // restart slow from the beginning
	for slow != fast {
		slow = nums[slow] // both go one hop now
		fast = nums[fast]
	}
	return slow // the loop entrance is the duplicate
}

func main() {
	fmt.Println(findDuplicate([]int{3, 1, 3, 4, 2})) // 3
}

Time: O(n) · Extra space: O(1). A few laps of the trail at most, and only two markers of memory. A hash set would use O(n) space.

Watch out for

  • Starting slow and fast at different places in the first phase, or checking equality before moving, so the loop ends instantly.
  • Forgetting to check fast and fast.next for null on a real linked list (an array trail like this one never ends, so it is safe).
  • Believing the first meeting point is the loop entrance. It is only somewhere in the loop; a second walk finds the entrance.

Quick check

  1. A problem says "detect a cycle using O(1) extra memory". Which pattern?
    • Fast/slow pointers
    • Prefix sum
    • Binary search
  2. How many steps does fast take compared with slow?
    • The same
    • Half as many
    • Twice as many
  3. When fast reaches the end of a list, where is slow?
    • At the end
    • At the start
    • At the middle