Green goblin
Green goblin

Reputation: 9996

Skipping more than one node in Floyd's cycle finding Algorithm

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.

Upvotes: 1

Views: 478

Answers (1)

Saeed Amiri
Saeed Amiri

Reputation: 22555

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.

Upvotes: 4

Related Questions