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 = 0 to 10 steps, it's on node 0, 1, 2, 3, 4, 5, 6, 7, 3, 4, 5. Here , the steps to the loop, and , the loop's length:
| Walk | Steps | Ends on |
|---|---|---|
| slow | node 5 | |
| fast | node 5 | |
| from the head | node 3, the loop's start | |
| from the meeting point | node 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 , and fast has taken . Here .
They stand on the same node, and they can only share a node on the loop. So the extra steps that fast took went around the loop a whole number of times: is a multiple of . Here , one lap.
The meeting point is steps from the head. Walk it more steps and it's steps from the head. That's the start of the loop, steps in, plus whole laps.
The pointer from the head reaches the start after the same 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 : the meeting tells you when you've walked it.