17/39
Part 4 of 7 · Cycles and meeting pointsLearn

Restart one pointer at the head, step both by one, and they meet where the loop starts

Put one pointer back at the head, leave the other at the meeting point, and move both one step at a time:

node, meet = head, slow
step = 0
print(f"step {step}: from the head on {node.val}, from the meeting point on {meet.val}")
while node is not meet:
    node, meet = node.next, meet.next
    step += 1
    print(f"step {step}: from the head on {node.val}, from the meeting point on {meet.val}")
step 0: from the head on 0, from the meeting point on 5
step 1: from the head on 1, from the meeting point on 6
step 2: from the head on 2, from the meeting point on 7
step 3: from the head on 3, from the meeting point on 3

They meet again on node 3, the start of the loop. To see why, write down where a walk from the head stands: after tt = 0 to 10 steps, it's on node 0, 1, 2, 3, 4, 5, 6, 7, 3, 4, 5. Here μ=3\mu = 3, the steps to the loop, and λ=5\lambda = 5, the loop's length:

WalkStepsEnds on
slowi=5i = 5node 5
fast2i=102i = 10node 5
from the headμ=3\mu = 3node 3, the loop's start
from the meeting pointμ=3\mu = 3node 3

From t = 3 on, the node repeats every 5 steps, once per lap of the loop. That one fact gives the whole argument.

When they meet, slow has taken some number of steps ii, and fast has taken 2i2i. Here i=5i = 5.

They stand on the same node, and they can only share a node on the loop. So the extra ii steps that fast took went around the loop a whole number of times: ii is a multiple of λ\lambda. Here i=5=λi = 5 = \lambda, one lap.

The meeting point is ii steps from the head. Walk it μ\mu more steps and it's μ+i\mu + i steps from the head. That's the start of the loop, μ\mu steps in, plus whole laps.

The pointer from the head reaches the start after the same μ\mu steps. Before that, it's still on the part before the loop while the other one is on the loop, so they can't meet sooner. You never need to know μ\mu: the meeting tells you when you've walked it.