Fast and slow pointers: the middle, and finding a cycle
🌍 In real life. On sports day two friends start a race together: the tortoise walks, the hare runs twice as fast. On a straight road, the hare simply reaches the end first, and at that moment the tortoise is exactly halfway. On the circular track round the school field, the hare never reaches an end; it laps the field and, sooner or later, comes up behind the tortoise and lands on the same spot.
Two markers moving at different speeds along a linked list answer two questions with one walk: where is the middle? and does the list loop back on itself?
The idea in one sentence: start slow and fast at the head, move slow 1 node and fast 2 nodes per turn: if fast reaches the end, slow is at the middle; if fast ever lands on the same node as slow, the list has a cycle.
Its words:
- slow and fast pointers (the tortoise and the hare): two references walking the same list at speeds 1 and 2
- cycle: some node's next points back to an earlier node (or to itself), so walking never reaches None
The middle, step by step:
slow = fast = head- while
fast and fast.next:slow = slow.next,fast = fast.next.next - slow is the middle (for an even length, the second of the two middle nodes)
Finding a cycle, step by step: the same loop, and after each move check if slow is fast:. Here the last node's next points back to 3:
Why it is correct.
- The middle: after t turns slow has taken t steps and fast 2t. The loop stops when fast can't take 2 more steps, that is when 2t has reached the end, so slow, at t, is halfway.
- A cycle: without one, fast runs off the end into None and the loop stops: no cycle. With one, both runners end up going round it. From then on, each turn fast gains exactly 1 node on slow, so the gap between them shrinks by 1 every turn and must reach 0: they land on the same node, within one lap of the cycle.
What it costs. Both run in one pass over the list, O(n) time, with just two references: O(1) memory. The other way to find a cycle, remembering every node you have visited in a set, is also O(n) time but needs O(n) memory.
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def middle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow.val
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast: # the same node, not just the same value
return True
return False
nodes = [Node(v) for v in [1, 2, 3, 4, 5, 6]]
for a, b in zip(nodes, nodes[1:]):
a.next = b
print(middle(nodes[0]), has_cycle(nodes[0]))
nodes[-1].next = nodes[2] # make a cycle back to 3
print(has_cycle(nodes[0]))Mistakes and edge cases.
- writing
while fast.next.next:: when fast is the last node,fast.nextis None andNone.nextraisesAttributeError; checkfast and fast.next - comparing values (
slow.val == fast.val) instead of nodes (slow is fast): a list like 1 → 1 → 1 without a cycle would look like one middleof an empty list: there is no node to give back, so decide first (the tasks start with at least one node)- for the first of two middles, loop
while fast.next and fast.next.nextinstead
Quiz
What does this print?
class Node: def __init__(self, val, next=None): self.val = val self.next = next head = Node(10, Node(20, Node(30, Node(40)))) slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next print(slow.val)Once both runners are inside a cycle, why must fast land on slow?
- Each turn fast gains exactly 1 node, so the gap shrinks by 1 until it is 0
- fast jumps 2, so it could skip over slow forever
- Because the values in a cycle repeat
has_cycle says True for 1 → 1 → 1, which has no cycle. Which line is wrong?
def has_cycle(head): slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow.val == fast.val: return True return FalseWhat memory do the tortoise and hare need, compared with a set of visited nodes?
- O(1) for the runners, O(n) for the set
- Both O(n)
- O(n) for the runners, O(1) for the set
Coding tasks
Write
middle(head)with slow and fast pointers: the value of the middle node (the second middle for an even length). The list has at least one node.Write
has_cycle(head)with slow and fast pointers, in O(1) extra memory: True if following next from head ever comes back to a node already passed, False if it reaches None.