This is an algorithm to detect cycles in a Linked List. It uses 2 pointers, one slow moving and other fast. See for more details.

Starting from the node head, the slow pointer goes to head->next and the fast pointer goes to head->next->next. The algorithm terminates if any of the next field is null, as that means there’s no cycle present. It finds a cycle if both the slow and fast pointer point to the same node. We can also find out the starting point of the cycle with this

Why does it work?

  • If there’s a cycle, all pointers starting from head and following next will eventually just be moving between nodes of the cycle.
  • The distance between the fast and slow moving pointers increases by 1 after each step.

Combining the above points, both the fast and slow pointers will eventually be moving between nodes of the cycle. As their distance increases by 1 each time, eventually their distance will become a multiple of the length of the cycle. At that time, they will be pointing to the same node.

Consider the above cycle, the slow and fast pointers will move as shown in the following table. Slow and Fast column contains the node index. Distance means the number of links to follow to get from slow to fast.

IterationSlowFastDistance
1110
2231
3352
4473
5544
6665

The algorithm terminates at iteration 6. Note that the distance between the pointers becomes a multiple of cycle length at which point they will be pointing the same node.

Finding the starting point of the cycle

After having determined there is a cycle, reset the slow pointer to point to head. Now move both slow and fast pointers 1 node at a time. They will meet at the starting point of the cycle.

Consider the above figure. is the distance travelled by the pointers to enter the cycle, is the distance travelled from the starting point of the cycle and is the length of the cycle.

Since fast pointer moves at twice the speed of slow pointer, it will have covered twice the distance. Which means

Consider what happens after slow pointer is set to head. The slow pointer has to follow distance to reach the head of the cycle. Acoording to the last equation we can see that even the fast pointer will reach the head of the cycle after travelling distance . This is because it is at distance from the start, and is a multiple of the length of the list.