Fast and slow pointers
Two pointers walk the same list at different speeds, usually one step and two steps at a time. When the fast one reaches the end, the slow one is in the middle. If the list has a loop, the fast one laps the slow one and they meet. A fixed gap between them finds the n-th node from the end.
How to recognise it
- Find the middle, or split the list into two halves, in one pass.
- Detect a loop, find where it starts, or measure it, with O(1) extra memory.
- Find or remove the n-th node from the end without counting the length first.
The idea in one picture
Two runners on a track. If the track is a straight road, the faster one reaches the end first, and the slower one is exactly halfway at that moment. If the track is a loop, the faster runner comes up behind the slower one and laps them. Both facts are useful, and neither needs a count of the nodes.
Three uses
| Use | Setup | Stop when | Answer |
|---|---|---|---|
| Middle | both on the head, speeds 1 and 2 | fast or fast.next is null | slow |
| Loop | both on the head, speeds 1 and 2 | slow == fast (loop) or fast ends (no loop) | met or not |
| n-th from the end | both on a dummy, fast first moves n steps | fast.next is null | slow is just before it |
Template: speeds 1 and 2
slow = head, fast = head
while fast is not null and fast.next is not null:
slow = slow.next
fast = fast.next.next
(for loops: if slow == fast: there is a loop)
Finding where a loop starts
Let the loop start L steps from the head and have length C. When they meet, slow has walked L + x steps and fast
2(L + x), and fast's extra L + x steps are whole laps. So L + x is a multiple of C, and walking L more steps
from the meeting point lands on the loop start. Put one pointer on the head and walk both one step at a time: they meet
at the start.
Common mistakes
- Checking
fast.next.nextwithout checkingfast.next, which crashes on even lengths. - Comparing values instead of nodes when testing whether slow and fast met.
- Expecting the first middle when the loop gives the second (or the other way round). Start fast one step ahead to get the first middle.
- Forgetting the dummy node when the node to remove may be the head.
Problems
- Middle of the Linked Listeasyguide ready
- Palindrome Linked Listeasyguide ready
- Linked List Cycleeasyguide ready
- Remove Nth Node From End of Listmediumguide ready
- Delete the Middle Node of a Linked Listmediumguide ready
- Linked List Cycle IImediumguide ready
- Length of loop in LLmediumguide ready
- Write a program to Delete loop in a linked listmediumguide ready