Sub topic 12
Detecting a cycle with Floyd's algorithm
This chapter assumes you can write a singly linked list with Node objects and a next reference, and that you can walk one with a while loop. It also assumes you know introductory Big-O notation. You should have seen slow and fast pointers in the previous chapter.
What a cycle is and why it matters
A linked list is normally a chain that ends when a node's next is None. A cycle exists when some node's next points back to a node earlier in the chain. After that, following next forever never reaches None.
The usual traversal loop, while current is not None, never stops on such a list. Cycles come from bugs such as relinking a tail to the wrong node, a failed deletion, or a merge that reuses nodes. They can also be intentional, as in the circular lists from the earlier chapter. Detection answers the question "does this chain end?" before you walk it.
Three terms are used throughout this chapter:
- The tail length (call it μ) is the number of nodes before the cycle begins. In the diagram, μ is 2.
- The cycle length (call it λ) is the number of nodes in the loop. In the diagram, λ is 3.
- The entry node is the first node that belongs to the loop. In the diagram, it is node 3.
The straightforward approach: remember what you saw
You can walk the list and record each node you visit. If you reach a node already recorded, there is a cycle. If you reach None, there is not.
def has_cycle_with_set(head):
seen = set()
current = head
while current is not None:
if id(current) in seen:
return True
seen.add(id(current))
current = current.next
return FalseThis runs in O(n) time but uses O(n) extra memory. It records id(current) rather than the node, so the set tracks object identity instead of using any __eq__ or __hash__ the node class might define. For a list with millions of nodes the set is a real cost. Floyd's algorithm gets the same answer with O(1) extra memory.
Floyd's tortoise and hare
Floyd's algorithm uses two references that start at the head. The slow pointer (the tortoise) moves one node per step. The fast pointer (the hare) moves two nodes per step.
- If the list has no cycle, the fast pointer reaches
Noneand the loop ends. - If the list has a cycle, both pointers eventually enter it, and the fast pointer catches the slow one from behind.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def has_cycle(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:
return True
return FalseThe loop condition has two parts, and their order matters. fast is not None must be checked first. If it were skipped, fast.next on a None fast pointer would raise AttributeError. fast.next is not None must be checked before fast.next.next is evaluated, for the same reason. Python's and stops at the first false operand, so the order shown is safe.
Why the pointers must meet
Suppose both pointers are inside the cycle, and the fast pointer is d nodes behind the slow one, measured along the direction of travel. Each step, the slow pointer advances 1 node and the fast pointer advances 2. The gap changes by 1 each step: d, d−1, d−2, and so on, wrapping around the cycle.
The gap shrinks by exactly 1, so it cannot jump over zero. When it reaches 0, both pointers are on the same node. If the hare moved 3 nodes per step, the gap would shrink by 2. That can skip over zero when the cycle length is even, which is why the 1-versus-2 speed pair is the standard choice.
The slow pointer enters the cycle after μ steps. By then the fast pointer is already inside. Once the slow pointer enters, the gap is less than λ, so the pointers meet within λ more steps. Total work is at most μ + λ steps for the slow pointer, which is O(n).
A worked trace
Take the list from the diagram: 1 → 2 → 3 → 4 → 5, with 5 pointing back to 3.
| Step | slow | fast |
|---|---|---|
| start | 1 | 1 |
| 1 | 2 | 3 |
| 2 | 3 | 5 |
| 3 | 4 | 4 |
After step 3 both pointers are on node 4, so slow is fast is true. On step 3, fast moves from 5 to 3 to 4.
Comparing with `is`, not `==`
Compare the pointers with is. A cycle is about whether two references point to the same node object. Two different nodes can hold equal values, for example 3 twice in a list. If you wrote slow == fast and the class defined __eq__ to compare values, you would report cycles in lists that have none. Comparing slow.value == fast.value has the same problem. Use is.
Finding where the cycle starts
Knowing a cycle exists is often not enough. To repair the list, you need the entry node. Floyd's algorithm has a second phase for this.
- Run the first phase until
slow is fast. - Move one pointer back to
head. Leave the other at the meeting point. - Advance both pointers one node at a time. They meet at the entry node.
def find_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 NoneWhy phase two works
Let k be the number of steps taken before the first meeting. The slow pointer has moved k nodes and the fast pointer has moved 2k nodes. Both are at the same node, so the fast pointer has made extra loops around the cycle: 2k − k = k is a multiple of λ.
Now consider the meeting node. It is k nodes from the head. Moving μ more nodes from there reaches position k + μ. Because k is a multiple of λ, going k steps along the cycle returns to where you started, so position k + μ is the same node as position μ. Position μ is the entry node. A pointer that starts at the head and moves μ steps also reaches the entry node. Both pointers move at the same speed and cover μ steps, so they arrive there together. You never need to know μ itself.
In the example, the meeting node is 4 and μ is 2. The head pointer goes 1 → 2 → 3, and the meeting pointer goes 4 → 5 → 3. Both reach node 3 after two steps.
Measuring the cycle length
After the first meeting, keep one pointer fixed and walk another around the loop until it returns. The number of steps is λ.
def cycle_length(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:
length = 1
current = slow.next
while current is not slow:
current = current.next
length += 1
return length
return 0The function returns 0 when there is no cycle.
Running all three functions
This script assumes Node, has_cycle, find_cycle_start, and cycle_length are defined as above.
nodes = [Node(v) for v in range(1, 6)]
for a, b in zip(nodes, nodes[1:]):
a.next = b
head = nodes[0]
print(has_cycle(head)) # False
print(find_cycle_start(head)) # None
print(cycle_length(head)) # 0
nodes[-1].next = nodes[2] # node 5 now points back to node 3
print(has_cycle(head)) # True
print(find_cycle_start(head).value) # 3
print(cycle_length(head)) # 3Edge cases
| Input | Result | Reason |
|---|---|---|
| Empty list (`head` is `None`) | No cycle | The loop condition fails immediately. |
| One node, `next` is `None` | No cycle | `fast.next` is `None`, so the loop does not run. |
| One node pointing to itself | Cycle | After one step both pointers are on that node. |
| Two nodes pointing to each other | Cycle | The pointers meet after the first or second step. |
| Cycle that includes the head | Cycle, entry node is the head | Phase two starts with `slow` already at the entry node. |
For a cycle that includes the head, μ is 0. The meeting point is k nodes from the head with k a multiple of λ. The meeting node is therefore the head itself, and the phase-two loop does not run.
Common mistakes
- Checking
fast.next.nextwithout first checkingfastandfast.next. On lists of even and odd length the fast pointer lands onNonein different places, so test both even and odd lengths. - Starting
fastone node ahead ofslowand checkingslow is fastbefore the first move. If both start athead, a check before moving reports a cycle on every non-empty list. - Resetting the wrong pointer in phase two, or moving the pointers at different speeds. Both must move one node per step.
- Assuming a cycle returns the head. The meeting node is generally not the entry node. Only phase two finds the entry.
- Mutating the list while detecting. A common alternative marks visited nodes in place, but that changes the data and is unsafe if other code reads the list.
Costs
| Approach | Time | Extra space | Modifies list |
|---|---|---|---|
| Visited set | O(n) | O(n) | No |
| Floyd's algorithm | O(n) | O(1) | No |
Floyd's algorithm does more pointer moves than the set approach in the no-cycle case, roughly 1.5 times the list length in node hops counting both pointers. Both are linear. Choose Floyd's when memory matters or when you cannot rely on node identity being hashable. The set approach is simpler to read and is fine for small lists.
Exercise
In the list 1 → 2 → 3 → 4 → 5 → 6 where node 6 points back to node 2, what are μ and λ, and which node does find_cycle_start return?
Show answer
The nodes before the cycle are 1, so μ = 1. The loop is 2, 3, 4, 5, 6, so λ = 5. find_cycle_start returns node 2, the first node in the loop.
Exercise
A learner changes the loop in has_cycle to while fast.next is not None and fast is not None:. On which input does it fail, and what error appears?
Show answer
It fails when fast becomes None, which happens on an odd-length list without a cycle, and on an empty list. fast.next is evaluated first and raises AttributeError: 'NoneType' object has no attribute 'next'. Checking fast is not None first avoids this.
Exercise
Write a function remove_cycle(head) that breaks the cycle by setting the last node's next to None, and returns True if it changed the list. Describe how you would find the last node using find_cycle_start.
Show answer
Find the entry node with find_cycle_start. If it returns None, return False. Otherwise start a pointer at the entry node and advance while pointer.next is not entry. At that point pointer is the last node in the loop, so set pointer.next = None and return True. If the entry node points to itself, the loop does not run and the same assignment still works.