Sub topic 12
Functional Graphs and Floyd's Tortoise and Hare
This chapter assumes you can read the Python in the earlier chapters, you know what a directed cycle is, and you are comfortable with Big-O notation. Earlier chapters detected cycles by walking an adjacency list and marking vertices. Here the graph has a stricter shape, and that shape lets you find a cycle with only two pointers and no visited set.
What a Functional Graph Is
A functional graph is a directed graph in which every vertex has exactly one outgoing edge. A function f from a finite set to itself defines one: the edge from x goes to f(x). A self-loop is allowed, and it means f(x) == x, which is a fixed point.
The graph is often never stored at all. You only have a way to compute the next state:
- In a linked list,
f(node) = node.next. - In a pseudo-random number generator,
f(seed)is the next seed. - In an array
awhose values are valid indices,f(i) = a[i].
Each vertex has one outgoing edge, so a walk from any start x0 is forced: x0, f(x0), f(f(x0)), .... The set is finite, so the walk must eventually repeat a value. From then on it repeats forever. There are no branches, so the only question is when the repetition starts and how long it lasts.
The Rho Shape: mu and lambda
Every such walk looks like the Greek letter rho (ρ): a tail that leads into a loop. Two numbers describe it:
mu(μ) is the index of the first element on the cycle. The tail isx0 ... x(mu-1).lam(λ) is the cycle length. For alli >= mu,x(i + lam) == x(i).
If x0 is already on the cycle, mu is 0. If the walk reaches a fixed point, lam is 1.
A whole functional graph on n vertices is a set of components. Each component has exactly one cycle, with trees of tail vertices hanging into it. Floyd's algorithm looks at only one component: the one that contains x0.
Why Not Just Use a Visited Set?
You could store each value with its index in a dictionary and stop at the first repeat. That takes O(mu + lam) time and O(mu + lam) memory. When the states are large, such as big integers in a factoring algorithm, or the cycle has millions of elements, that memory is the bottleneck. Three-color DFS from earlier chapters has the same cost, and it also needs the vertices to be indexable.
Floyd's tortoise-and-hare algorithm runs in O(mu + lam) time with O(1) extra memory. It only needs to call f and to compare two states for equality.
The Algorithm
def floyd_cycle(f, x0):
tortoise, hare = f(x0), f(f(x0))
while tortoise != hare:
tortoise, hare = f(tortoise), f(f(hare))
mu, tortoise = 0, x0
while tortoise != hare:
tortoise, hare = f(tortoise), f(hare)
mu += 1
lam, hare = 1, f(tortoise)
while tortoise != hare:
hare = f(hare)
lam += 1
return mu, lamThe function runs in three phases.
Phase 1: Getting a Meeting
After t iterations, the tortoise is at x(t) and the hare is at x(2t). Once both are on the cycle (t >= mu), the gap between them grows by one each step, measured around the cycle. A gap that grows by one must eventually equal a multiple of lam, so the pointers meet within lam more steps. The meeting index i satisfies two facts that matter:
i >= mu, because the tortoise is on the cycle.2i - i = iis a multiple oflam, becausex(2i) == x(i)on the cycle.
Phase 1 takes at most mu + lam iterations.
Phase 2: Finding mu
Reset the tortoise to x0 and leave the hare at x(i). Move both one step at a time. After k steps, the tortoise is at x(k) and the hare is at x(i + k). When k = mu, the hare is at x(mu + i). Since i is a multiple of lam, that equals x(mu), so they meet there.
They cannot meet earlier. For k < mu, the tortoise is on the tail and the hare is on the cycle, and tail and cycle share no vertices. So the number of steps counted is exactly mu.
Phase 3: Finding lam
The tortoise now sits on the cycle at x(mu). Keep it still and move the hare until it comes back. The number of steps is lam.
A Worked Trace
Take f on the set {0, ..., 9} given by the list F = [2, 0, 5, 9, 1, 7, 6, 3, 8, 5], starting at x0 = 0. The walk is 0, 2, 5, 7, 3, 9, 5, 7, 3, 9, .... The tail is 0, 2, so mu = 2. The cycle is 5, 7, 3, 9, so lam = 4.
| Phase 1 step t | tortoise x(t) | hare x(2t) | equal? |
|---|---|---|---|
| 1 | 2 | 5 | no |
| 2 | 5 | 3 | no |
| 3 | 7 | 5 | no |
| 4 | 3 | 3 | yes |
They meet at i = 4, which is a multiple of lam = 4. In phase 2 the tortoise starts at 0 and the hare at 3. They move to (2, 9), then (5, 5), so mu = 2. In phase 3 the hare walks 7, 3, 9, 5 from the tortoise at 5, so lam = 4.
F = [2, 0, 5, 9, 1, 7, 6, 3, 8, 5]
print(floyd_cycle(lambda x: F[x], 0)) # (2, 4)
print(floyd_cycle(lambda x: F[x], 6)) # (0, 1): 6 is a fixed point
print(floyd_cycle(lambda x: F[x], 4)) # (3, 4): 4 -> 1 -> 0 -> 2 -> 5Linked Lists: When the Walk Can End
A linked list is not quite a functional graph, because the last node points to None. That gives a walk with no cycle, and calling f(None) would crash. So the hare must check for the end before each of its two steps:
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def list_cycle_start(head):
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow is fast:
slow = head
while slow is not fast:
slow = slow.next
fast = fast.next
return slow
return None
nodes = [Node(i) for i in range(6)]
for a, b in zip(nodes, nodes[1:]):
a.next = b
print(list_cycle_start(nodes[0])) # None: no cycle yet
nodes[-1].next = nodes[2]
print(list_cycle_start(nodes[0]).val) # 2This version uses is because two different nodes can hold equal values. The phase 2 logic is the same as in floyd_cycle.
Gotchas
- Equality must match identity of states. Compare states, not labels. Two list nodes with equal
valare different vertices. Two floating-point states that print the same may not compare equal. - The set must be finite or the walk must end. If
fcan produce unboundedly many states, as inf(x) = x + 1, phase 1 never ends. Add an end check like the linked-list version, or cap the number of steps. - Count calls to f, not loop iterations. Phase 1 makes three calls to
fper iteration. Whenfis expensive, such as a hash or a modular multiplication, Brent's algorithm finds the samemuandlamwith fewer calls. It works by teleporting the tortoise to the hare at powers of two. - Floyd's algorithm covers one component. To find every cycle in an explicit functional graph stored as an array, use the coloring approach from the three-color DFS chapter. Each vertex has one out-edge, so this runs in O(n) total. Running Floyd's algorithm from every vertex would cost O(n²) in the worst case.
Where It Shows Up
- Duplicate detection in an array. An array of length
n + 1holds values in1..n. Treati -> a[i]asf. The repeated value is the cycle entryx(mu)starting from index 0, found in O(1) extra space without modifying the array. - Pollard's rho factorization walks
x -> x² + c mod nand uses Floyd's or Brent's meeting test to find a factor. - Generator periods. Measuring
lamfor a pseudo-random generator, or for any iterated map, shows how soon its output repeats.
Exercise
For F = [1, 2, 3, 4, 2] and x0 = 0, give mu and lam, and state the index i at which phase 1 of floyd_cycle stops.
Show answer
The walk is 0, 1, 2, 3, 4, 2, 3, 4, ... so the tail is 0, 1 (mu = 2) and the cycle is 2, 3, 4 (lam = 3). Phase 1 compares x(t) with x(2t): t=1 gives 1 vs 2, t=2 gives 2 vs 4, t=3 gives 3 vs 3, so it stops at i = 3, a multiple of lam with i >= mu.
Exercise
In phase 2, why must the hare stay where phase 1 left it instead of also being reset to x0?
Show answer
The proof needs the hare to be exactly i steps ahead of the tortoise, where i is a multiple of lam. Then once the tortoise reaches x(mu), the hare is at x(mu + i) = x(mu). If both started at x0, they would always be equal and the loop would end immediately with mu = 0.
Exercise
You are given a callable next_state(s) over a huge but finite state space, and each call takes 1 ms. You need lam only. Which method from this chapter would you pick, and why?
Show answer
Use Brent's algorithm, or Floyd's algorithm if simplicity matters more. Both need O(1) memory, which a visited set over a huge state space would not give you. Brent's algorithm makes fewer calls to next_state, and that matters when each call costs 1 ms. If you only need lam, you can stop after the phase that measures the cycle length and skip computing mu.