Learn / Linked lists

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

UseSetupStop whenAnswer
Middleboth on the head, speeds 1 and 2fast or fast.next is nullslow
Loopboth on the head, speeds 1 and 2slow == fast (loop) or fast ends (no loop)met or not
n-th from the endboth on a dummy, fast first moves n stepsfast.next is nullslow 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.next without checking fast.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

0 of 8 solved

Check yourself

slow moves 1 step and fast moves 2. In a list of 6 nodes, where is slow when fast can move no further?

Why must fast and slow meet if there is a loop?

After slow and fast meet inside the loop, one pointer goes back to the head and both move one step at a time. Where do they meet?

To remove the n-th node from the end, how far ahead should fast start?