45

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?

Paul R
  • 208,748
  • 37
  • 389
  • 560
Derek Li
  • 3,089
  • 2
  • 25
  • 38
  • 7
    There's a somewhat faster modification of the algorithm, if anyone is curious: http://www.siafoo.net/algorithm/11 – Dave Sep 26 '11 at 05:30

3 Answers3

83

Because maybe not the complete linkedList is within the loop.

For a linked list lasso detection algorithm, you need two pointers:

enter image description here

As long as the first pointer is where the cowboy is, no loop is detected. But if you move it stepwise forward, it will eventually enter the loop.


BTW, lasso is the terminus technicus from graph theory, cowboy isn't.

DaveFar
  • 7,078
  • 4
  • 50
  • 90
56

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.)

Paul R
  • 208,748
  • 37
  • 389
  • 560
  • 1
    That's clears it up. Thanks all, since I can only mark one correct answers I will mark the earliest one. – Derek Li Sep 13 '11 at 08:35
27

Because the loop may not contain the element pointed to by the first pointer.

For example, if the first pointer points to element 1 and the linked list has a loop later on (1->2->3->4->2), your algorithm won't detect it.

DaveFar
  • 7,078
  • 4
  • 50
  • 90
flight
  • 7,162
  • 4
  • 24
  • 31
  • just removed some minor typos so I can give you the 50+ in a week with good conscience (since you just missed being accepted by a couple of seconds). – DaveFar Sep 20 '11 at 10:22
  • @DaveBall Wow. Thanks. I'm glad you noticed. ;) – flight Sep 20 '11 at 10:28