Consider the following linked list:
1->2->3->4->5->6->7->8->9->4->...->9->4.....
The above list has a loop as follows:
[4->5->6->7->8->9->4]
Drawing the linked list on a whiteboard, I tried manually solving it for different pointer steps, to see how the pointers move around -
(slow_pointer_increment, fast_pointer_increment)
So, the pointers for different cases are as follows:
(1,2), (2,3), (1,3)
The first two pairs of increments - (1,2) and (2,3) worked fine, but when I use the pair (1,3), the algorithm does not seem to work on this pair. Is there a rule as to by how much we need to increment the steps for this algorithm to hold true?
Although I searched for various increment steps for the slower and the faster pointer, I haven't so far found a single relevant answer as to why it is not working for the increment (1,3) on this list.
Bernhard Barker explanation is spot on. I am simply adding on to it.
Why should the difference of speeds between the pointers and the cycle length be coprime numbers?
Take a scenario where the difference of speeds between pointers(say
v) and cycle length(sayL) are not coprime. So there exists a GCD(v,L) greater than 1 (sayG).Therefore, we have
v=difference of speeds between pointersL=Length of the cycle(i.e. the number of nodes in the cycle)G=GCD(v,L)Since we are considering only relative positions, essentially the
slowis stationary and thefastis moving at a relative speedv. Letfastbe at some node in the cycle.Since
Gis a divisor ofLwe can divide the cycle into G/L parts. Start dividing from wherefastis located.Now,
vis a multiple ofG(sayv=nG). Every time thefastpointer moves it will jump acrossnparts. So in each part the pointer arrives on a single node(basically the last node of a part). Each and every time thefastpointer will land on the ending node of every part. Refer the image belowExample image
As mentioned above by Bernhard, the question we need to answer is Can we reach every position moving at some speed?
The answer is no if we have a GCD existing. As we see the
fastpointer will only cover the last nodes in every part.