Sub topic 9
Slow and Fast Pointers
This chapter assumes you can build and traverse a singly linked list with Node objects that have value and next fields. It also assumes you know Big-O notation at an introductory level. The code uses Python.
The idea
A linked list gives you no index. To reach the middle node, you cannot compute len(items) // 2 and jump there. You have to walk from the head.
The slow and fast pointer technique (also called the two-pointer or runner technique) walks the list with two references at once. Both start at the head and move along next links, but they move at different rates or from different starting points. The distance between them then encodes information about the list, such as where the middle is or how far you are from the end. You get that information in one pass, with no extra memory.
There are two common variants:
| Variant | How the pointers move | What it finds |
|---|---|---|
| Different speeds | `slow` moves 1 node per step, `fast` moves 2 | The middle node; whether a cycle exists |
| Fixed gap | `lead` moves ahead by `n` nodes first, then both move 1 per step | The nth node from the end |
This chapter covers both variants. Using different speeds to detect a cycle is covered in the chapter on Floyd's algorithm.
All examples below use this setup.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def build(values):
head = None
for v in reversed(values):
head = Node(v, head)
return head
def to_list(head):
out = []
while head is not None:
out.append(head.value)
head = head.next
return outFinding the middle node
fast moves twice as far as slow on every step. When fast runs off the end of the list, slow has covered half the distance, so it sits at the middle.
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
print(middle(build([1, 2, 3, 4, 5])).value) # 3
print(middle(build([1, 2, 3, 4])).value) # 3The loop condition checks two things, in this order:
fast is not Nonehandles an empty list and an even-length list, wherefastlands onNoneafter a double step.fast.next is not Nonehandles an odd-length list, wherefastlands on the last node. Without this check,fast.next.nextwould raiseAttributeErroronNone.
The order matters. Python evaluates and left to right and stops early, so the second check never runs when fast is already None.
Which middle for even lengths?
An even-length list has two middle nodes. The loop above returns the second one. For [1, 2, 3, 4] it returns 3.
Sometimes you need the first one. A common case is splitting a list into two halves, where you must cut the link after the first half. Change the loop condition so fast stops one step earlier:
def first_middle(head):
if head is None:
return None
slow = fast = head
while fast.next is not None and fast.next.next is not None:
slow = slow.next
fast = fast.next.next
return slow
print(first_middle(build([1, 2, 3, 4, 5])).value) # 3
print(first_middle(build([1, 2, 3, 4])).value) # 2Odd-length lists give the same answer for both versions. Only even-length lists differ. Decide which middle you need before you write the loop, and test both an even and an odd list.
Trace for five nodes
| Step | `slow` | `fast` |
|---|---|---|
| Start | 1 | 1 |
| After step 1 | 2 | 3 |
| After step 2 | 3 | 5 |
| Check | `fast.next` is `None`, so stop |
The function returns node 3.
Finding the nth node from the end
A singly linked list cannot be walked backwards, so "the 2nd node from the end" is awkward. The simple approach makes two passes. The first pass counts the nodes, and the second walks length - n steps. That is O(n) time and works fine.
The gap technique does the same job in a single pass. Move a lead pointer n nodes ahead, then move lead and trail together. When lead falls off the end, trail is exactly n nodes from the end, because the gap between them never changed.
def nth_from_end(head, n):
if n < 1:
raise ValueError("n must be at least 1")
lead = head
for _ in range(n):
if lead is None:
return None # the list has fewer than n nodes
lead = lead.next
trail = head
while lead is not None:
lead = lead.next
trail = trail.next
return trail
print(nth_from_end(build([1, 2, 3, 4, 5]), 2).value) # 4
print(nth_from_end(build([1, 2, 3, 4, 5]), 5).value) # 1
print(nth_from_end(build([1, 2, 3]), 4)) # NoneBoth versions are O(n) time and O(1) extra space. The single-pass version helps most when the list is long, when reading it is costly, or when it arrives as a stream you can only traverse once. For a small in-memory list, a two-pass version is just as correct and arguably easier to read.
Removing the nth node from the end
Deleting needs the node before the target, as in the deletion chapter. A sentinel node, covered in an earlier chapter, makes the head case disappear. Start trail on the sentinel, and when lead reaches the end, trail is already the predecessor of the node to remove.
def remove_nth_from_end(head, n):
if n < 1:
raise ValueError("n must be at least 1")
dummy = Node(None, head)
lead = head
for _ in range(n):
if lead is None:
raise ValueError("list has fewer than n nodes")
lead = lead.next
trail = dummy
while lead is not None:
lead = lead.next
trail = trail.next
trail.next = trail.next.next
return dummy.next
print(to_list(remove_nth_from_end(build([1, 2, 3, 4, 5]), 2))) # [1, 2, 3, 5]
print(to_list(remove_nth_from_end(build([1, 2, 3]), 3))) # [2, 3]The second call removes the head. Without the sentinel, you would need a separate branch for that case.
Why the pointers behave this way
For the speed variant, fast covers two nodes for every one that slow covers. When fast has traveled the whole length L, slow has traveled about L / 2. That gives the middle without ever knowing L.
For the gap variant, the invariant is that lead is always exactly n links ahead of trail. When lead is None, it has moved n links past the last node, so trail is n nodes back from the end.
Because the work is a single loop in which each pointer moves at most L times, both techniques run in O(n) time. They keep only two references, so extra space is O(1).
Common mistakes
- Dereferencing
None. Writingwhile fast.next is not Nonecrashes on an empty list. Writingfast.next.nextwithout checkingfast.nextcrashes on odd-length lists. Check each link before you follow it. - An off-by-one in the gap. Advancing
leadbyn - 1orn + 1returns the wrong node, or the wrong predecessor when deleting. Test withn = 1,nequal to the length, andnlarger than the length. - Not handling an empty list. Most of these loops quietly work on
None, butfirst_middleshows a version that needs an explicit check. - Running on a list with a cycle. If the list loops back on itself,
fastnever reachesNone, somiddleloops forever. The same behavior is what makes cycle detection possible.
Where else the technique appears
- Palindrome check. Find the middle, reverse the second half in place, then compare both halves node by node.
- Splitting a list. Merge sort on a linked list uses the first middle to cut the list in two.
- Cycle detection. If
fastever catches up toslow, the list contains a cycle. The next chapters cover circular lists and Floyd's algorithm in detail.
Exercise
In middle, the loop condition is while fast is not None and fast.next is not None. What goes wrong if you swap the two checks so that fast.next is not None comes first? Which input shows the failure?
Show answer
The swapped condition evaluates fast.next before checking fast. On an even-length list, fast becomes None after a double step, so None.next raises AttributeError. A list of two nodes such as [1, 2] shows it: after one step, fast is None, and the condition crashes instead of ending the loop. An empty list fails too, because head is None from the start. The original order works because and stops at the first false check and never reaches fast.next.
Exercise
Using the gap technique, nth_from_end(build([1, 2, 3, 4, 5]), 1) is called. After the for loop, where does lead point, and what does the function return?
Show answer
After 1 step, lead points at node 2, while trail is at node 1. The while loop then moves both pointers until lead is None. That takes 4 steps and moves trail from node 1 to node 5. The function returns node 5, the last node, which is the 1st from the end.