learngraphtheory.org

Guest

Sign in to keep your graphs and progress.

Algorithm Selection

Select an algorithm and generate steps to begin visualization

Floyd's Cycle Detection

Two runners, one cycle, no memory

Two pointers walk a functional graph at speeds one and two: they meet inside the cycle, then find where it starts and how long it is, with O(1) memory

Time: O(μ + λ)
Space: O(1)
Use Case: Linked-list cycles, the find-the-duplicate problem, testing random number generators, Pollard's rho
Showing the example graph for this algorithm.
Algorithm Execution

Select an algorithm and generate steps to begin visualization

About Floyd's Cycle Detection (Tortoise and Hare)

Floyd's cycle detection finds a loop in a sequence that is generated step by step: a linked list, where each node points to the next, or a function applied again and again, x, f(x), f(f(x)) and so on. As a graph, every vertex has at most one arc going out, a functional graph. Starting anywhere, the walk either stops or runs into a cycle and goes round it for ever. Its shape is the Greek letter rho: a tail of μ vertices leading into a cycle of λ vertices. The method finds μ, λ and the vertex where the tail joins the cycle with two pointers and nothing else.

How it works

Phase 1 sends a tortoise one arc per move and a hare two arcs per move from the start. If the hare reaches a vertex with no arc out, there is no cycle. Otherwise both end up inside the cycle, where the hare gains one arc per move and catches the tortoise after at most μ + λ moves. Phase 2 puts the tortoise back at the start and moves both one arc at a time: because the meeting point lies a multiple of λ beyond the start, they meet again exactly where the cycle begins, after μ moves. Phase 3 lets the hare go round once to count λ. Time is O(μ + λ) and space O(1), where a set of visited vertices would need O(μ + λ) memory. The visualizer marks the tortoise T and the hare H, draws the arcs each one walked, and colours the tail orange, the cycle green and its first vertex magenta.

Applications

The method is the standard answer to the linked-list cycle questions of coding interviews and to "find the duplicate number", where the array is read as a function from index to value. Pollard's rho factorisation uses it to find a repeat of x² + c modulo a hidden factor, which is where the name rho comes from. It also measures the period of random number generators and detects loops in iterated hash chains. Brent's variant, which teleports the tortoise at powers of two, does the same job with fewer function calls.

Pseudocode

Three phases with two pointers. f(x) stands for the vertex that the single arc out of x leads to.

FloydCycle(f, s):                  // f(x) = where the one arc out of x leads
    tortoise = s, hare = s
    repeat:                        // phase 1: speeds 1 and 2
        if f(hare) or f(f(hare)) does not exist: return NO CYCLE
        tortoise = f(tortoise)
        hare = f(f(hare))
    until tortoise == hare
    tortoise = s, mu = 0           // phase 2: both at speed 1
    while tortoise != hare:
        tortoise = f(tortoise), hare = f(hare), mu = mu + 1
    lambda = 1, hare = f(tortoise) // phase 3: once round the cycle
    while hare != tortoise:
        hare = f(hare), lambda = lambda + 1
    return mu, lambda, tortoise    // tortoise: the first cycle vertex

Phase 2 works because, when they first meet, the tortoise has made t moves and the hare 2t, and the difference t is a multiple of λ. So the meeting point is t arcs from the start, and walking μ more arcs from it lands on the first cycle vertex, exactly where a pointer from the start arrives after μ arcs.

Worked example, step by step

The example loaded on this page, started at A.

Example graph: Arcs A → B → C → D → E → F → G → H and H → D. The tail is A, B, C and the cycle is D, E, F, G, H.

  1. Phase 1, moves 1 to 3. The tortoise walks to B, C and D while the hare jumps to C, E and G. After three moves the tortoise has just entered the cycle at D.
  2. Phase 1, moves 4 and 5. The hare wraps round through H to D while the tortoise moves to E. One move later both stand on F: they meet after 5 moves.
  3. Why they met. The tortoise has walked 5 arcs and the hare 10. The difference, 5, is a multiple of the cycle length, which is what makes a meeting certain once both are in the cycle.
  4. Phase 2. The tortoise goes back to A and the hare stays at F. Moving one arc each, they reach B and G, then C and H, then both D. They meet after 3 moves, so μ = 3 and the cycle starts at D.
  5. Phase 3. The hare walks on through E, F, G and H and back to D: 5 arcs, so λ = 5.

Tail μ = 3 (A, B, C), cycle λ = 5 (D to H), cycle start D. Two pointers were enough: 5 moves to meet, 3 to find the start and 5 to measure the cycle.

Complexity, and where it comes from

Time: O(μ + λ) · Space: O(1)

In phase 1 the tortoise enters the cycle after μ moves. The hare is already in it and closes the gap by one arc per move, so they meet within λ more moves: at most μ + λ moves of three evaluations of f each. Phase 2 takes exactly μ moves and phase 3 exactly λ steps. Only two positions and two counters are stored, against O(μ + λ) for a set or map of visited vertices.

When to use Floyd's Cycle Detection (Tortoise and Hare), and when not to

Other ways to find the cycle of a sequence.

AlternativePrefer it whenCost
Visited set or hash mapMemory is plentiful and one pass is wanted. Storing the step at which each value was first seen gives μ and λ as soon as a value repeats.O(μ + λ) time and space
Brent's algorithmEvaluating f is expensive. Only the hare walks, and the tortoise jumps to it at powers of two, which typically saves about a third of the evaluations.O(μ + λ) time, O(1) space
DFS with three coloursThe graph is not functional: vertices have several arcs out, and the question is whether any cycle exists at all.O(n + m) time, O(n) space

Common pitfalls

  • Checking the hare only once per move. The hare moves two arcs, and both must exist. Test f(hare) before f(f(hare)), or a list that ends after an odd number of steps crashes on a null pointer.
  • Taking the meeting point for the cycle start. In this example they meet at F, but the cycle starts at D. The first meeting only proves that a cycle exists, phase 2 is needed to find where it begins.
  • Running it on a graph that branches. With two arcs out of one vertex there is no single next vertex, so the walk is not defined. Floyd needs a function, such as a linked list or x → f(x). The visualizer stops and names the vertex with too many arcs.

Frequently asked questions

Why speeds one and two?
Inside the cycle the gap between them then shrinks by exactly one arc per move, so the hare cannot skip past the tortoise and they must meet. With speeds one and three the gap shrinks by two, and on a cycle of even length they may never meet. Speeds one and two also make phase 2 work, because the meeting point lies a multiple of λ from the start.
How does it find the duplicate number in an array?
In an array of n + 1 numbers from 1 to n, read each index i as a vertex with an arc to a[i]. Every vertex has one arc out, and no arc enters index 0, so the walk from 0 has a tail and then a cycle. The cycle starts at a value that two indices point to: the duplicate.
Where does the rho in Pollard rho come from?
Drawn on paper, a tail leading into a cycle looks like the Greek letter ρ. Pollard rho factorisation walks x → x² + c modulo n and uses Floyd to notice when the walk repeats modulo an unknown prime factor p, which a gcd with n then reveals.

Related algorithms: Cycle Detection, Depth-First Search, Tarjan's SCC Algorithm, Topological Sort, Eulerian Path (Undirected)

An example graph: you can change it, or start blank.

Zoom Controls

30%
Nodes: 8
Edges: 8