AlgoTales · Roadmap

Floyd's cycle detection

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Floyd's method finds a loop using two walkers on the chain: a slow one stepping once and a fast one stepping twice. If there is a loop, the fast one eventually catches up to the slow one. If the chain ends, the fast one just reaches the end. It needs no extra memory.

Practical use cases

  • Web app: A job chain that never finishes. A background worker follows "next job" links stored in a table, and one bad row points back to an earlier job. The worker keeps running the same jobs forever and sends the same emails. A tiny guard that advances a second pointer twice as fast detects the loop within a few steps and halts the run.
  • Web app: Health check on imported linked data. An import tool reads millions of rows linked by next_id from a client's CSV. Keeping a set of all visited ids would use a lot of server memory. Two pointers use almost none, so the import can flag a corrupted chain without slowing or crashing the server.
  • System: Low-memory devices and infinite-loop checks. Embedded devices and tools that inspect broken data structures often have no room to remember every visited item. Floyd's method needs only two pointers, which makes it the go-to loop check when memory is tight. Debuggers and memory inspectors use it too, to avoid hanging on broken data they are only trying to examine.

The story: The Tortoise and the Hare on the Maidan

On the school ground there was a round running track, and Sports Day was coming. Coach Rathore wanted to know: "If I put one slow runner and one fast runner on this track, will the fast one meet the slow one again?" Kabir said, "Only if the track is a loop. On a straight road the fast runner just finishes and goes home."

That gave Mira an idea for the cycle puzzle. "We do not need chalk marks. Send two walkers along the list: Tortoise takes one step, Hare takes two. If the list ends, the hare gets to null first: no cycle. If there is a loop, both end up circling inside it, and the hare gains one step per round on the tortoise. Eventually the hare lands exactly on the tortoise."

Why can it never jump over the tortoise? Because it gains only one step per round. If the gap between them is 3, it becomes 2, then 1, then 0, meeting. It cannot skip from 1 straight to "overtaken".

This is Floyd's cycle detection (the tortoise and hare algorithm). It answers "is there a cycle?" in O(n) time with only O(1) memory. Last lesson you chalked every node. Now you need nothing but two pointers.

How to spot this problem, and where you need it

You must find out whether a chain of links loops back on itself, but you cannot afford to remember every item you pass, either because memory is tight or the chain is huge.

Signs you need it

  • The task says "detect a cycle using constant extra space" or "do not use a hash set".
  • The chain could have millions of items, and storing all visited ids would eat the memory of a small server or device.
  • A walk along next pointers sometimes never ends in production, and you want a quick guard inside the loop.

Where to use it in a project

  • Guard conditions inside workers that follow next-job, next-page or redirect links.
  • Validators that scan huge imported datasets with linked rows.
  • Firmware or small scripts walking chains with very little memory.

The solution

Start two pointers at the head. In every round move the slow pointer one step and the fast pointer two steps. If the fast pointer ever lands on the same item as the slow one, there is a loop. If the fast pointer runs off the end, there is none. The fast one gains one step per round on the slow one, so inside a loop they must meet.

Payoff: Before: a set holding millions of ids. After: two variables, and a loop is found in a number of steps close to the chain length.

Explain it like I am 8

Two kids run round a track, one twice as fast. On a track with a loop, the fast kid keeps catching up from behind and eventually bumps into the slow kid. On a road that ends, the fast kid just runs off the end and never meets anybody.

How it works, step by step

  1. Start both pointers, slow and fast, at the head.
  2. Repeat: move slow by one node and fast by two nodes.
  3. If fast (or fast.next) becomes null, the list ends: no cycle.
  4. If slow and fast are ever on the same node, there is a cycle.
  5. Why it works: inside a loop the fast pointer closes the gap by one node every round, so it cannot leap over the slow one.

The code in four languages

PHP

<?php
class Node {
    public $val;
    public ?Node $next = null;
    public function __construct($val) { $this->val = $val; }
}

// returns the node where tortoise and hare meet, or null if there is no cycle
function floyd(?Node $head): ?Node {
    $slow = $head;
    $fast = $head;
    while ($fast !== null && $fast->next !== null) {
        $slow = $slow->next;            // tortoise: one step
        $fast = $fast->next->next;      // hare: two steps
        if ($slow === $fast) return $slow;   // they met, so there is a loop
    }
    return null;                        // hare fell off the end: no loop
}

$nodes = [];
for ($i = 1; $i <= 6; $i++) { $nodes[$i] = new Node($i); }
for ($i = 1; $i < 6; $i++) { $nodes[$i]->next = $nodes[$i + 1]; }

$m = floyd($nodes[1]);
echo 'Straight list: ' . ($m === null ? 'no cycle' : 'cycle') . "\n";
$nodes[6]->next = $nodes[3];             // make 6 point back to 3
$m = floyd($nodes[1]);
echo 'With loop     : ' . ($m === null ? 'no cycle' : 'cycle, they met at node ' . $m->val) . "\n";

JavaScript

class Node {
  constructor(val) { this.val = val; this.next = null; }
}

// returns the node where tortoise and hare meet, or null if there is no cycle
function floyd(head) {
  let slow = head;
  let fast = head;
  while (fast !== null && fast.next !== null) {
    slow = slow.next;              // tortoise: one step
    fast = fast.next.next;         // hare: two steps
    if (slow === fast) return slow;   // they met, so there is a loop
  }
  return null;                     // hare fell off the end: no loop
}

const nodes = [];
for (let i = 1; i <= 6; i++) nodes[i] = new Node(i);
for (let i = 1; i < 6; i++) nodes[i].next = nodes[i + 1];

let m = floyd(nodes[1]);
console.log('Straight list: ' + (m === null ? 'no cycle' : 'cycle'));
nodes[6].next = nodes[3];          // make 6 point back to 3
m = floyd(nodes[1]);
console.log('With loop    : ' + (m === null ? 'no cycle' : 'cycle, they met at node ' + m.val));

Java

public class Main {
    static class Node {
        int val;
        Node next = null;
        Node(int val) { this.val = val; }
    }

    // returns the node where tortoise and hare meet, or null if there is no cycle
    static Node floyd(Node head) {
        Node slow = head;
        Node fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;              // tortoise: one step
            fast = fast.next.next;         // hare: two steps
            if (slow == fast) return slow; // they met, so there is a loop
        }
        return null;                       // hare fell off the end: no loop
    }

    public static void main(String[] args) {
        Node[] nodes = new Node[7];
        for (int i = 1; i <= 6; i++) nodes[i] = new Node(i);
        for (int i = 1; i < 6; i++) nodes[i].next = nodes[i + 1];

        Node m = floyd(nodes[1]);
        System.out.println("Straight list: " + (m == null ? "no cycle" : "cycle"));
        nodes[6].next = nodes[3];          // make 6 point back to 3
        m = floyd(nodes[1]);
        System.out.println("With loop    : " + (m == null ? "no cycle" : "cycle, they met at node " + m.val));
    }
}

Go

package main

import "fmt"

type Node struct {
	val  int
	next *Node
}

// floyd returns the node where tortoise and hare meet, or nil if there is no cycle.
func floyd(head *Node) *Node {
	slow, fast := head, head
	for fast != nil && fast.next != nil {
		slow = slow.next      // tortoise: one step
		fast = fast.next.next // hare: two steps
		if slow == fast {
			return slow // they met, so there is a loop
		}
	}
	return nil // hare fell off the end: no loop
}

func main() {
	nodes := make([]*Node, 7)
	for i := 1; i <= 6; i++ {
		nodes[i] = &Node{val: i}
	}
	for i := 1; i < 6; i++ {
		nodes[i].next = nodes[i+1]
	}

	m := floyd(nodes[1])
	if m == nil {
		fmt.Println("Straight list: no cycle")
	} else {
		fmt.Println("Straight list: cycle")
	}
	nodes[6].next = nodes[3] // make 6 point back to 3
	m = floyd(nodes[1])
	if m == nil {
		fmt.Println("With loop    : no cycle")
	} else {
		fmt.Println("With loop    : cycle, they met at node", m.val)
	}
}

Time: O(n) · Extra space: O(1). The hare meets the tortoise within a couple of laps of the loop, and we keep just two pointers.

Watch out for

  • Moving the hare three or more steps and assuming it still works: it can still be proven, but two is the standard and easiest to reason about.
  • Checking fast.next.next without first checking that fast and fast.next exist, which crashes on short lists.
  • Comparing values instead of the nodes themselves. Compare identity: slow === fast.

Quick check

  1. What happens to fast and slow on a list with NO cycle?
    • They meet in the middle
    • fast reaches null
    • slow reaches null first
    • They swap places
  2. How much memory does Floyd's algorithm need?
    • A set of all nodes
    • A copy of the list
    • An array of indexes
    • Just two pointers
  3. Why can the hare never jump over the tortoise inside the loop?
    • It gains only one step per round, so the gap shrinks by one each time
    • It moves slower inside loops
    • The tortoise waits for it
    • Loops are always short