Fast and slow pointers
Move one 1 step and another 2. In a they must meet; in a straight list the fast one stops at the end, the slow one at the middle.
The idea
moving at different speeds reveal the shape of a without extra memory. If there's a cycle, the fast pointer laps the slow one and they meet. If there isn't, the fast pointer reaches the end.
When fast reaches the end, slow has gone half as far: it's at the middle.
Worked example
Middle of 1 → 2 → 3 → 4 → 5
- slow 1, fast 1 → slow 2, fast 3 → slow 3, fast 5 → fast can't move two more → middle is 3
Pseudocode
The steps in plain words. ← means “set to”; indentation shows what's inside what.
See it run
The worked example, step by step, beside the Python. The highlighted line is the one running.
Step-by-step
1 → 2 → 3 → 4 → 5
Solution · Pythonline 2
def has_cycle(head):slow = fast = headwhile fast and fast.next:slow, fast = slow.next, fast.next.nextif slow is fast:return Truereturn False def middle(head):slow = fast = headwhile fast and fast.next:slow, fast = slow.next, fast.next.nextreturn slowStep 1 of 4· line 2
SLOW moves one node per step, FAST moves two. When FAST runs out of list, SLOW has gone exactly half as far: the middle.
time, space.
How to spot it
- , the middle , “find the duplicate number” in an array treated as a list.
Common mistakes
- Checking `fast.next.next` without checking `fast.next` first.
- Comparing values instead of the nodes themselves.
Practise the ideas first
One small exercise per idea, right in the editor, before the problems below.
Practise it
Go further
Up next for you · Beginner
“Have I seen this?” is a set →