1

Today I was reading Floyd's algorithm of detecting loop in a linked list. I was just wondering that won't it be better if we skip more than one node, (say 2) for faster loop detection?

For example:

fastptr=fastptr->next->next->next.

Note that the side effects will be taken into account while changing fastptr.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Green goblin
  • 9,898
  • 13
  • 71
  • 100
  • If you skip more than 1, you might miss the loop detection at the earliest point. – leppie Jun 12 '12 at 06:48
  • 1
    @leppie, can you give one such example? – Green goblin Jun 12 '12 at 06:51
  • Even worse, you might not detect the loop at all. Consider a loop with length 6 where the hare is at node 0 when the tortoise is at node 1. If the hare moves three steps for every step of the tortoise, the subsequent tortoise/hare positions are 2/3, 3/0, 4/3, 5/0, 0/3, 1/0, 2/3 ad infinitum and the existence of the loop is never detected. – ottomeister Jun 15 '12 at 08:06
  • ... except that I don't see a way of getting to the necessary initial conditions for such an infinite loop. Dangit, now I'm going to be awake all night thinking about this. – ottomeister Jun 15 '12 at 08:49

1 Answers1

4

Your suggestion still is correct, but it doesn't change the speed of algorithm. If you take a look at tortoise and hare algorithm in wiki:

The key insight in the algorithm is that, for any integers i ≥ μ and k ≥ 0, xi = xi + kλ, where λ is the length of the loop to be found and μ is start position of loop. In particular, whenever i = kλ ≥ μ, it follows that xi = x2i.

In the bold part, you could also say xi = x3i, or any other coefficient, but key insight is finding the i, it's not important with how many jumps you will find it, and order of algorithm, depends to the location of i.

Saeed Amiri
  • 22,252
  • 5
  • 45
  • 83