Sub topic 9
Slow and Fast Pointers
This chapter assumes you can build and traverse a singly linked list with Node objects, as in the earlier chapters, and that you know Big-O notation at an introductory level. Here you will learn the two-pointer technique: walking a list with two references that move at different speeds.
The idea
A singly linked list gives you no length and no index. To find the middle, you would normally count the nodes in one pass, then walk halfway in a second pass. Two pointers do the same job in one pass.
- The slow pointer moves one node per step.
- The fast pointer moves two nodes per step.
When the fast pointer reaches the end, the slow pointer has covered half the distance. It is standing at the middle.
Finding the middle node
This function assumes the Node class from earlier chapters, with value and next fields.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def middle(head):
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
return slow
head = Node(1, Node(2, Node(3, Node(4, Node(5)))))
print(middle(head).value) # 3The loop condition checks fast is not None first, and then fast.next is not None. Python stops evaluating at the first false test. Reversing the order would raise an AttributeError on an empty list or an even-length list, because fast can become None.
For an even number of nodes, this version returns the second of the two middle nodes. On 1, 2, 3, 4 it returns the node holding 3. If you need the first middle node, change the loop condition to fast.next is not None and fast.next.next is not None.
Finding a cycle
A list has a cycle if some node's next points back to an earlier node. A plain traversal would then loop forever. Slow and fast pointers detect this without extra memory.
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 FalseWithout a cycle, fast reaches None and the loop ends. With a cycle, both pointers enter the loop and stay in it. Each step, the gap between them changes by one node, because fast gains one position on slow. The gap cannot jump over zero, so the two pointers must land on the same node. The next chapters cover this as Floyd's algorithm.
Note the comparison uses is, not ==. You are asking whether both names refer to the same node object, not whether two nodes hold equal values.
Costs
| Task | Time | Extra space |
|---|---|---|
| Find the middle | O(n) | O(1) |
| Detect a cycle | O(n) | O(1) |
A common alternative for cycle detection is to store every visited node in a set. That is also O(n) time, but it uses O(n) memory. The two-pointer version needs only two references.
Common errors
- Checking
fast.nextbefore checkingfast. This fails whenfastisNone. - Starting
fastone node ahead ofslowwithout adjusting the loop. This shifts which middle node you get on even-length lists. - Comparing values instead of nodes when looking for a cycle. Lists with repeated values would report cycles that do not exist.
- Forgetting the empty list. With
head = None, both pointers start asNone, the loop never runs, andmiddlereturnsNone. Callers must handle that.
Exercise
Write middle_first(head), which returns the first of the two middle nodes when the list has an even length. For 1, 2, 3, 4 it must return the node holding 2, and for 1, 2, 3 the node holding 2.
Show answer
Change the loop condition so that fast must be able to take a full two-step move before the slow pointer advances: def middle_first(head): slow = fast = head while fast is not None and fast.next is not None and fast.next.next is not None: slow = slow.next fast = fast.next.next return slow On 1, 2, 3, 4: fast starts at 1, and fast.next.next is node 3, so one step moves slow to 2 and fast to 3. Then fast.next.next is None, so the loop stops and slow is node 2. On 1, 2, 3: one step moves slow to 2 and fast to 3, then fast.next is None, so the loop stops with slow at 2.