Fast and slow pointers: why they meet
1 A road, and maybe a track
An array finds its middle with one index. A linked list cannot. We have only the head, and each node knows only the next one. Two questions about a list come up again and again:
- Where is the middle? We could count the nodes, then walk again to half the count. That is two walks.
- Does the list end, or loop back? The last node can point back to an earlier node. Then a walk with
curnever reaches null and never stops.
One idea answers both. Two pointers start at the head. slow moves one node at a time, and fast moves two. These are the fast and slow pointers.
The picture to keep is two runners, one twice as fast as the other. They set off together down a road. If the road just ends, the fast runner reaches the end when the slow one is halfway. If the road leads onto a running track, the fast runner goes round and comes up behind the slow one.
Every value in this list is different, so we name each node by its value.
2 The middle in one walk
First, a list with no loop: the road just ends. fast covers two nodes for every one that slow covers. So when fast reaches the end, slow has covered half the list. Here are the first five nodes of our list:
fast stops when it cannot take two more steps. That happens when fast is null, or when it is on the last node.
With six nodes, there are two middles, 2 and 7. Which one we get depends on when fast stops:
| Keep moving while these exist | 5 nodes | 6 nodes |
|---|---|---|
fast and fast.next | 2 | 7, the second middle |
fast.next and fast.next.next | 2 | 2, the first middle |
Middle of the Linked List wants the second middle. To split a list into two halves, we often want the first, so that slow is the last node of the first half.
C++
Check fast first. && stops at the first false part, so fast->next is never read when fast is nullptr.
Check fast first. && stops at the first false part, so fast.next is never read when fast is null.
Check fast first. and stops at the first false part, so fast.next is never read when fast is None.
Check fast first. && stops at the first false part, so fast.next is never read when fast is null.
Check fast first. && stops at the first false part, so fast.Next is never read when fast is nil.
fast counts, then slow walks. While fast borrows the list, we cannot also move nodes out of it for slow. So fast counts how many moves slow would make, and slow makes them afterwards. It is still O(n) time and O(1) space.
Check fast first. && stops at the first false part, so fast.next is never read when fast is null.
3 On a loop, fast catches slow
Now the whole list, where 8 points back to 2. fast never finds an end. It reaches the track first and goes round and round. Once slow is on the track too, fast closes in on it from behind. We compare the two pointers after every move:
So the loop ends in one of two ways. The pointers meet, so the list has a cycle. Or fast runs out of list, so it has none. Linked List Cycle asks exactly this:
C++
slow == fast compares addresses. It is true only when both pointers hold the same node, never for two nodes with the same value.
== compares references. It is true only when both hold the same node object, never for two nodes with the same value.
Use is. slow is fast asks whether both names hold the same node, which is the question here.
=== on objects compares identity. It is true only when both hold the same node, never for two nodes with the same value.
Pointers compare by address. slow == fast is true only when both point to the same node.
A loop needs Rc<RefCell<ListNode>>. With Box, every node has one owner, so no node can point back to an earlier one. The practice problems with cycles use Rc, which lets two nodes share the same next node. Rc::ptr_eq checks whether two pointers hold the same node.
== compares references here. ListNode is a class and does not change ==, so it is true only when both hold the same node.
4 Why they cannot miss each other
fast moves two nodes at a time. It looks as if it could jump over slow and keep missing it, lap after lap. It cannot, and the reason is one number.
The gap is how many steps fast is behind slow, counted forwards along the track. In each move, slow walks 1 step away from fast, and fast walks 2 steps towards slow. So the gap gets smaller by exactly 1:
| Move | slow on | fast on | Gap |
|---|---|---|---|
| 2 | 2 | 5 | 3 |
| 3 | 7 | 8 | 2 |
| 4 | 5 | 7 | 1 |
| 5 | 1 | 1 | 0 |
The gap starts at 3 when slow reaches the track. Then it goes 2, 1, 0. A number that drops by exactly 1 each time cannot skip 0. So fast lands on slow. It never jumps over it.
The speed of 2 matters. At speed 3, the gap drops by 2 each move. A gap of 3 goes to 1 and then past 0, and on a track of even length an odd gap stays odd forever.
The gap is also smaller than the track's length L, because it is a distance along the track. So they meet within L moves after slow arrives, before slow finishes its first lap. Our track has 5 nodes, the gap starts at 3, and they meet 3 moves later.
5 Where the track starts
Linked List Cycle II asks for the node where the loop starts: node 2 in our list. The meeting node already holds the answer. We need three distances:
- a = 2, from the head to the start: 4 → 9 → 2.
- b = 3, from the start to the meeting node: 2 → 7 → 5 → 1.
- L = 5, the length of the track.
slow made a + b = 5 moves to reach the meeting node. fast made twice as many, 10. Both ended on the same node, so fast's extra 5 moves took it round the track and back. Those extra moves are always whole laps.
Now stand on the meeting node. It is b = 3 steps into the track, so L − b = 2 more steps reach the start: 1 → 8 → 2. That is exactly a. The head is also a steps from the start. So two pointers that each take one step at a time, one from the head and one from the meeting node, reach the start together:
On a long road and a short track, fast may go round several times before slow arrives. Then its extra a + b moves are k laps, not one, so a + b = k × L:
From the meeting node, a steps still reach the start: L − b steps to get there, then k − 1 whole laps that end where they began. We never calculate a. We only walk it. After the pointers meet, the second phase is short:
slow = head // fast stays put
while slow != fast:
slow = slow.next
fast = fast.next // one step
return slow
The track's length needs one more walk. Keep one pointer on the meeting node, and walk the other round until it comes back, counting the steps.
6 Any walk with a next rule
Nothing above used the values in the nodes. It used one fact: every node has exactly one next. Any walk like that has the same shape, a road and maybe a track, and the same two pointers work on it.
Find the Duplicate Number gives n + 1 values, each from 1 to n, and one value repeats. We treat each index as a node, and nums[i] as the arrow out of index i. For nums = [2, 5, 1, 4, 3, 4], the walk from index 0 goes:
Index 4 has two arrows coming in, from index 5 and from index 3, because both hold the value 4. The node where the track starts always has two arrows in: one from the road and one from the end of the track. So the repeated value is the start of the track, and the last section finds it with no extra memory.
The nodes can be plain numbers too. In Happy Number, the next of a number is the sum of the squares of its digits. The walk either reaches 1 and stays there, or goes round a loop without 1. The two pointers tell these apart without storing every number seen.
7 Cost and mistakes
The cost comes from the same picture. slow reaches the track, then meets fast within L more moves. The road and the track hold n nodes in all, so slow makes at most n moves and fast at most 2n. With no loop, fast reaches the end in about n/2 moves. Either way it is O(n) time. The two pointers are the only memory, so it is O(1) space.
A set of visited nodes also finds a loop in O(n) time, but it holds up to n nodes, so it takes O(n) space. Find the Duplicate Number forbids that extra memory, and interviewers often ask for O(1) as the follow-up.
Four mistakes come up again and again:
- Checking
fast.nextbeforefast. On the 6-node list,fastbecomes null after three moves. Reading its next then gives a Runtime Error. Checking onlyfastfails the other way: on the 5-node list,fastreaches the last node, wherefast.next.nextcrashes. - Starting
fastathead.next. It changes which middle we get: on the 6-node list,slowends on 2, not 7. In Linked List Cycle II, it moves the meeting node to 5, and the second phase then circles forever without meeting, so it gets TLE. - Comparing values instead of nodes. On
[5, 5, 5]with no loop,slowandfastsit on two different nodes that both hold 5, and the code reports a cycle. - Comparing before the first move. Both pointers start on the head, so a check at the top of the loop finds them equal at once, on every list.
8 When to use fast and slow pointers
The sign is a linked list, or any walk with a next rule, and a question about its shape. Three shapes come up:
- The middle. Palindrome Linked List and sorting a list both split the list at its middle first. When we need the node before the middle, as in Delete the Middle Node,
faststarts two nodes ahead, soslowstops one node earlier. - A loop. We can ask whether the list loops, where the loop starts, and how long it is. The walk can be a list, an array of indexes or a rule on numbers.
- A node counted from the end. Here both pointers move at the same speed, with a fixed gap.
fastmoves k nodes first, then both move one at a time. Whenfastruns off the end,slowis on the k-th node from the end. Removing that node also needs the node before it, and the next lesson's dummy node makes that easy at the head.
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.