algorithmlinked-listfloyd-cycle-finding

Linked list loop detection algorithm


I read some interview question online about how would you find if there's a loop in a linked list, and solution (Floyd's cycle-finding algorithm) is to have two pointers, one is 2x faster than the other, and check if they meet again.

My question is: Why can't I just keep one pointer fixed, just move the other pointer forward by 1 step each time?


Solution

  • Because the first (non-moving) pointer might not lie within the loop, so the pointers would never meet. (Remember that a loop may consist of only part of the list.)