Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Cycle Detection: Floyd & Brent

Tortoise and hare, the cycle’s start and length, and Pollard’s rho.

Iterate any function on a finite set, x0,x1=f(x0),x2=f(x1),…x_0, x_1 = f(x_0), x_2 = f(x_1), \dots, and some value must eventually repeat, after which the sequence cycles forever: its trace is shaped like the Greek letter ρ\rho. Finding the cycle with a hash set of visited values is easy; finding it while storing just two values is Floyd's tortoise and hare. The same idea factors integers (Pollard's rho, 1975), and it underlies the best known generic attack on the discrete logarithms behind elliptic-curve cryptography.

What you’ll learn

  • Model iteration on a finite set as a functional graph, and define the tail length μ\mu and the cycle length λ\lambda.
  • Prove that Floyd's tortoise and hare meet within μ+λ\mu + \lambda steps, and find μ\mu and λ\lambda with O(1)O(1) extra memory.
  • Describe Brent's power-of-two method, and compare the function evaluations of the two algorithms.
  • Apply cycle detection to linked lists, duplicates in read-only arrays and Pollard's rho, and explain why rho's O(p)O(\sqrt p) bound is a heuristic.

Every iteration ends in a cycle

A function f:S→Sf : S \to S on a finite set SS of nn elements is a functional graph: every element has exactly one outgoing arrow. Start anywhere and follow the arrows. Among x0,x1,…,xnx_0, x_1, \dots, x_n two values must coincide, since there are n+1n + 1 of them, and from the first repetition on, the sequence repeats forever.

A linked list with a cycle is the special case where ff means "follow next": μ\mu is the index of the first node on the cycle and λ\lambda the cycle's length. For a random function on nn points the birthday paradox sets the scale (Flajolet & Odlyzko, 1990): the expected tail and cycle lengths are both πn/8≈0.63n\sqrt{\pi n/8} \approx 0.63\sqrt n, and the expected number of distinct values visited, μ+λ\mu + \lambda, is πn/2≈1.25n\sqrt{\pi n/2} \approx 1.25\sqrt n.

Predict before you look

For a random function on n=106n = 10^6 points, about how many distinct values does the sequence x0,x1,…x_0, x_1, \dots visit, on average, before it first repeats?

Show the answer

1250

πn/2=π⋅106/2≈1253\sqrt{\pi n / 2} = \sqrt{\pi \cdot 10^6 / 2} \approx 1253: the birthday paradox, not n/2n/2. Over 400 random functions on 10610^6 points, our simulation averaged μ≈599\mu \approx 599, λ≈639\lambda \approx 639 and μ+λ≈1237\mu + \lambda \approx 1237, against the predicted 627, 627 and 1253.

Floyd's tortoise and hare

python
def floyd(f, x0):
    t, h = f(x0), f(f(x0))          # phase 1: t = x_i and h = x_{2i}, for i = 1, 2, ...
    while t != h:
        t, h = f(t), f(f(h))
    mu, t = 0, x0                   # phase 2: restart t; both move one step at a time
    while t != h:
        t, h, mu = f(t), f(h), mu + 1
    lam, h = 1, f(t)                # phase 3: walk once around the cycle
    while t != h:
        h, lam = f(h), lam + 1
    return mu, lam

Two stored values, whatever nn is. Knuth attributes the method to Robert W. Floyd (The Art of Computer Programming, vol. 2, §3.1, exercise 6); Floyd never published it as a paper. Tested against a hash-set search on random functions.

DerivationProof
  1. xi=x2i  ⟺  (i≥μ and λ∣i)⟹ν  ≤  max⁡(μ,1)+λ−1  ≤  μ+λx_i = x_{2i} \iff \big(i \ge \mu \text{ and } \lambda \mid i\big) \qquad\Longrightarrow\qquad \nu \;\le\; \max(\mu, 1) + \lambda - 1 \;\le\; \mu + \lambda

    Phase 1. After ii steps the tortoise is at xix_i and the hare at x2ix_{2i}. By the definition of μ\mu and λ\lambda, they coincide exactly when i≥μi \ge \mu and λ\lambda divides 2i−i=i2i - i = i. The smallest such i≥1i \ge 1 is ν\nu, and among any λ\lambda consecutive integers starting from max⁡(μ,1)\max(\mu, 1), one is a multiple of λ\lambda:

  2. xj=xν+j  ⟺  j≥μ⟹meeting point=xμx_j = x_{\nu + j} \iff j \ge \mu \qquad\Longrightarrow\qquad \text{meeting point} = x_\mu

    Phase 2. Restart the tortoise at x0x_0 and leave the hare at xνx_\nu; after jj more steps they are at xjx_j and xν+jx_{\nu + j}. Because ν\nu is a multiple of λ\lambda, these are equal exactly when j≥μj \ge \mu. So they first meet after j=μj = \mu steps, at the first node of the cycle:

  3. min⁡{ k≥1:xμ+k=xμ }  =  λ\min\{\,k \ge 1 : x_{\mu + k} = x_\mu\,\} \;=\; \lambda

    Phase 3. From xμx_\mu, the first return to xμx_\mu takes exactly λ\lambda steps, by the definition of λ\lambda.

Brent's algorithm: fewer evaluations

Floyd's phase 1 evaluates ff three times per step: twice for the hare, and once for the tortoise, which walks over values the hare has already computed. Brent's algorithm (1980) keeps only the hare moving. The tortoise waits at a fixed position and, whenever the hare has made a power-of-two number of steps since the tortoise's last move, jumps to the hare's position:

python
def brent(f, x0):
    power = lam = 1
    t, h = x0, f(x0)
    while t != h:                    # phase 1: finds lam directly
        if power == lam:             # a new power of two: teleport the tortoise
            t, power, lam = h, 2 * power, 0
        h, lam = f(h), lam + 1
    t = h = x0                       # phase 2: put h exactly lam steps ahead of t
    for _ in range(lam):
        h = f(h)
    mu = 0
    while t != h:                    # they meet at the cycle's first node
        t, h, mu = f(t), f(h), mu + 1
    return mu, lam

Once the tortoise sits on the cycle and the current window of 2k2^k steps is at least λ\lambda, the hare returns to it after exactly λ\lambda steps, so the counter lam is the cycle length. Phase 2 uses the fact that a pointer λ\lambda steps ahead meets the trailing one exactly at xμx_\mu. Tested against a hash-set search.

Random functions on 10610^6 points, 400 trialsFloydBrent
evaluations of ff until the cycle is detectedabout 3,030about 1,960
evaluations to find both μ\mu and λ\lambdaabout 4,870about 3,790
worst case of the detection phase, over all μ,λ<300\mu, \lambda < 3003(μ+λ)3(\mu + \lambda)just under 3(μ+λ)3(\mu + \lambda)
Our simulation. On average Brent's detection needs about a third fewer evaluations; the worst cases are comparable (for Brent, a cycle just longer than a power of two, such as μ=0\mu = 0 and λ=257\lambda = 257, costs 768 evaluations). Brent's paper used the saving to speed up Pollard's rho.

More memory buys fewer evaluations. Storing distinguished points, values with a rare property that is easy to test, such as many trailing zero bits, lets a walk recognize the cycle shortly after entering it, and lets many machines walk one huge function in parallel and notice when their walks collide (van Oorschot & Wiener, 1999). Large cryptanalytic collision searches are organized this way.

Check your understanding

A sequence has tail length μ=7\mu = 7 and cycle length λ=3\lambda = 3. After how many steps of phase 1 do Floyd's tortoise and hare first meet?

  1. 7
  2. 10
  3. 9
  4. 21
Show the answer

C. 9

They meet at the smallest i≥1i \ge 1 with i≥μi \ge \mu and λ∣i\lambda \mid i: the smallest multiple of 3 that is at least 7, which is 9. Check: the tortoise is at x9x_9 and the hare at x18x_{18}, both on the cycle, and 18−9=918 - 9 = 9 is a multiple of 3.

Applications: duplicates, generators and Pollard's rho

Finding a duplicate without extra memory. An array a[0..n]a[0..n] holds n+1n + 1 integers from 11 to nn, so some value repeats; find one without modifying the array, using O(1)O(1) extra space. Read the array as a function f(i)=a[i]f(i) = a[i] on {0,…,n}\{0, \dots, n\}. No value equals 0, so nothing points to index 0 and it lies on the tail. The cycle's first node xμx_\mu then has two predecessors, xμ−1x_{\mu - 1} on the tail and xμ+λ−1x_{\mu + \lambda - 1} on the cycle: two different indices holding the same value xμx_\mu. So the entrance is a duplicated value, and Floyd's algorithm finds it in O(n)O(n) time.

python
def find_duplicate(a):            # a holds n + 1 values from 1..n; read-only, O(1) extra space
    t = h = 0
    while True:                   # phase 1: meet inside the cycle
        t, h = a[t], a[a[h]]
        if t == h:
            break
    t = 0
    while t != h:                 # phase 2: meet at the cycle's entrance
        t, h = a[t], a[h]
    return t

On [3,1,3,4,2][3, 1, 3, 4, 2] the walk from index 0 is 0→3→4→2→3→⋯0 \to 3 \to 4 \to 2 \to 3 \to \cdots, so the cycle 3→4→23 \to 4 \to 2 is entered at 3, the duplicate. Tested on thousands of random arrays.

Pseudorandom generators are functions iterated on a finite state, so every one of them is eventually periodic; cycle detection measures the period of a generator, or of a hash function iterated on its own output, without storing the sequence.

Pollard's rho (1975) factors an integer NN. Iterate f(x)=x2+c mod Nf(x) = x^2 + c \bmod N. For an unknown prime factor pp of NN, the same sequence reduced mod pp is an iteration on only pp values, so it enters a cycle after roughly p\sqrt p steps, long before the sequence mod NN does. A collision mod pp shows up as gcd⁡(∣xi−x2i∣,N)>1\gcd(\abs{x_i - x_{2i}}, N) > 1, so Floyd's two pointers detect it without knowing pp.

python
from math import gcd

def pollard_rho(N, c=1, x0=2):    # N composite; returns a divisor of N, or N on failure
    f = lambda x: (x * x + c) % N
    t = h = x0
    d = 1
    while d == 1:
        t, h = f(t), f(f(h))
        d = gcd(abs(t - h), N)
    return d                      # d == N: retry with another c

For N=8051N = 8051 the sequence starts 2,5,26,677,7474,2839,8712, 5, 26, 677, 7474, 2839, 871, and at step 3, gcd⁡(∣677−871∣,8051)=97\gcd(\abs{677 - 871}, 8051) = 97, since 8051=83⋅978051 = 83 \cdot 97. For N=1,000,000,016,000,000,063=(109+7)(109+9)N = 1{,}000{,}000{,}016{,}000{,}000{,}063 = (10^9 + 7)(10^9 + 9) it finds 109+710^9 + 7 after 27,573 steps with c=1c = 1, the order of p≈31,600\sqrt p \approx 31{,}600, where trial division would need tens of millions of divisions even by primes alone.

Key takeaways

  • Iterating ff on a finite set traces a rho: a tail of μ\mu values, then a cycle of λ\lambda; for random functions on nn points, μ\mu and λ\lambda are about πn/8\sqrt{\pi n/8} each and μ+λ\mu + \lambda about πn/2\sqrt{\pi n/2}.
  • Floyd's tortoise and hare meet after ν=λ⌈μ/λ⌉≤μ+λ\nu = \lambda\lceil\mu/\lambda\rceil \le \mu + \lambda steps; restarting one pointer at x0x_0 finds μ\mu, and one lap finds λ\lambda, all while storing two values.
  • Brent's teleporting tortoise finds λ\lambda directly with about a third fewer evaluations on average; distinguished points trade memory for parallel collision search.
  • Cycle detection finds duplicates in read-only arrays, measures generator periods and powers Pollard's rho, whose O(p)O(\sqrt p) running time is a well-supported but unproved heuristic.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why do the two pointers in phase 2 of Floyd's algorithm meet exactly at the first node of the cycle?

  1. Because the hare moves twice as fast as the tortoise during phase 2
  2. Because the hare's lead ν\nu is a multiple of λ\lambda, so xj=xν+jx_j = x_{\nu + j} exactly when j≥μj \ge \mu, and the first such jj is μ\mu
  3. Because the meeting point of phase 1 is always the first node of the cycle
  4. Because μ\mu always equals λ\lambda
Show the answer

B. Because the hare's lead ν\nu is a multiple of λ\lambda, so xj=xν+jx_j = x_{\nu + j} exactly when j≥μj \ge \mu, and the first such jj is μ\mu

Two positions on the sequence hold the same value exactly when both are at least μ\mu and their distance is a multiple of λ\lambda. The distance is ν\nu, a multiple of λ\lambda, so the pointers agree as soon as the trailing one reaches index μ\mu, and not before, while it is still on the tail.

Question 2

To find a duplicate in an array of n+1n + 1 values from 11 to nn, Floyd's algorithm follows i↦a[i]i \mapsto a[i] starting at index 0. Why index 0?

  1. Because index 0 always holds the duplicate
  2. Because no value equals 0, so index 0 lies on the tail, and then the cycle's entrance has two different predecessors holding the same value
  3. Because starting anywhere else makes the walk leave the array
  4. Because index 0 is always on the cycle
Show the answer

B. Because no value equals 0, so index 0 lies on the tail, and then the cycle's entrance has two different predecessors holding the same value

The entrance xμx_\mu is reached from xμ−1x_{\mu-1} on the tail and from xμ+λ−1x_{\mu+\lambda-1} on the cycle: two different indices with the same value xμx_\mu, which is therefore a duplicate. That argument needs μ≥1\mu \ge 1, which starting at an index that nothing points to guarantees. Started on a cycle, the walk would have μ=0\mu = 0 and could return a value that is not duplicated.

Question 3

What does Brent's algorithm improve over Floyd's?

  1. It uses O(log⁡n)O(\log n) memory instead of O(1)O(1)
  2. It works for functions with several cycles reachable from x0x_0
  3. It needs about a third fewer evaluations of ff on average, finds λ\lambda directly, and still stores only two values
  4. It is guaranteed to stop after exactly μ+λ\mu + \lambda evaluations
Show the answer

C. It needs about a third fewer evaluations of ff on average, finds λ\lambda directly, and still stores only two values

Only the hare evaluates ff; the tortoise just jumps to the hare's position at powers of two. Our simulation on random functions of 10610^6 points: about 1,960 evaluations to detect the cycle against about 3,030 for Floyd. Its worst case is comparable to Floyd's, about 3(μ+λ)3(\mu + \lambda).

Question 4

What is known about the running time of Pollard's rho with f(x)=x2+cf(x) = x^2 + c for finding a prime factor pp of NN?

  1. It is proved to take O(p)O(\sqrt p) steps in the worst case
  2. It is proved to take O(log⁡N)O(\log N) steps
  3. The O(p)O(\sqrt p) bound is a heuristic, assuming x2+c mod px^2 + c \bmod p behaves like a random function; it is well supported by experiments but not proved
  4. It always takes about p/2p/2 steps, like trial division
Show the answer

C. The O(p)O(\sqrt p) bound is a heuristic, assuming x2+c mod px^2 + c \bmod p behaves like a random function; it is well supported by experiments but not proved

The birthday paradox gives about πp/2\sqrt{\pi p/2} steps for a random function on pp values. Whether the quadratic map is random enough has never been proved, although the method has worked as predicted in practice for decades.

Further reading

  • D. E. Knuth, The Art of Computer Programming, Vol. 2: Seminumerical Algorithms, 3rd ed. (Addison-Wesley, 1997), section 3.1 and section 4.5.4.
  • R. P. Brent, "An improved Monte Carlo factorization algorithm," BIT 20 (1980), 176–184.
  • J. M. Pollard, "A Monte Carlo method for factorization," BIT 15 (1975), 331–334.
  • P. Flajolet & A. M. Odlyzko, "Random mapping statistics," Advances in Cryptology: EUROCRYPT '89, Lecture Notes in Computer Science 434 (1990).
  • P. C. van Oorschot & M. J. Wiener, "Parallel collision search with cryptanalytic applications," Journal of Cryptology 12(1) (1999), 1–28.