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 know the idea of slow and fast pointers from the previous chapter. It also assumes introductory Big-O.
What a cycle is and why it matters
A list has a cycle when some node's next points back to an earlier node. Walking such a list never reaches None, so a plain while current is not None loop runs forever.
A cycle usually comes from a bug, such as relinking a node into the wrong place. A circular list has the same shape on purpose. The difference is intent: in a circular list you know to stop at the head, and in a damaged list you do not.
The algorithm
Floyd's algorithm uses two pointers that start at the head. The slow pointer moves one node per step. The fast pointer moves two nodes per step.
- If there is no cycle, the fast pointer reaches
Noneand the loop ends. - If there is a cycle, both pointers eventually run around it. The fast pointer gains one node on the slow pointer each step, so it must land on the same node.
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 False
# 1 -> 2 -> 3 -> 4 -> 5, then 5 points back to 3
nodes = [Node(v) for v in range(1, 6)]
for a, b in zip(nodes, nodes[1:]):
a.next = b
print(has_cycle(nodes[0])) # False
nodes[4].next = nodes[2]
print(has_cycle(nodes[0])) # TrueThe loop condition checks both fast and fast.next. The body reads fast.next.next, so if fast.next were None the code would raise an AttributeError.
Why the pointers must meet
Once both pointers are inside the cycle, look at the gap between them, measured along the cycle. Each step the slow pointer moves 1 and the fast pointer moves 2, so the gap shrinks by 1. A gap that shrinks by exactly 1 each step must reach 0. It cannot jump over 0, which is why a speed difference of one is enough.
The slow pointer enters the cycle after at most n steps, where n is the number of nodes. The fast pointer then closes the gap in at most the cycle length. The total is O(n) time. The algorithm stores only two references, so it uses O(1) extra space.
Comparing with a set of visited nodes
A simpler approach stores every visited node in a set and reports a cycle when a node repeats.
| Approach | Time | Extra space | Notes |
|---|---|---|---|
| Set of visited nodes | O(n) | O(n) | Easy to write and easy to extend |
| Floyd's slow and fast pointers | O(n) | O(1) | Needs no extra memory |
Use the set when memory is not a concern and clarity matters. Use Floyd's algorithm when the list is large or you cannot allocate extra storage.
Common errors
- Starting
fastathead.nextwhileslowstarts athead. This can still work, but theslow is fastcheck must then be placed carefully, so most code starts both athead. - Comparing values with
==instead of identity withis. Two different nodes can hold equal values, and that is not a cycle. - Forgetting the empty list. With
head = None, the loop condition is false at once and the function returnsFalse, which is correct. - Moving the pointers after the check instead of before it. At the start both are
head, so the check would report a false cycle.
Exercise
A list has 1 node, and its next points to itself. Does has_cycle return True, and after how many loop iterations?
Show answer
Yes. In the first iteration, slow moves to the node and fast moves two steps, which lands on the same node. They are identical, so the function returns True after one iteration.
Exercise
Why is the condition fast is not None and fast.next is not None needed, rather than just fast is not None?
Show answer
The loop body reads fast.next.next. If fast.next is None, that read fails with an AttributeError. Checking fast.next first stops the loop safely at the end of an even-length list or odd-length list without a cycle.