IntermediateLinked List

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

  1. 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.

slow ← head, fast ← head
while fast and fast.next exist:
slow ← slow.next(one step)
fast ← fast.next.next(two steps)
return slow(the middle)
for a cycle: if slow ever meets fast, there is one

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

1
▲ slow▲ fast
→
2
→
3
→
4
→
5
→ null

Solution · Pythonline 2

def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow is fast:
return True
return False
def middle(head):
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
return slow

Step 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

Practise it

Go further