This is NOT the problem about detecting cycle in a linked list using the famous Hare and Tortoise method.
In the Hare & Tortoise method we have pointers running in 1x and 2x speeds to determine that they meet and I am convinced that its the most efficient way and the order of that type of search is O(n).
The problem is I have to come up with a proof (proving or disproving) that it is possible that two pointers will always meet when the moving speed is Ax (A times x) and Bx (B times x) and A is not equal to B. Where A an B are two random integers operating on a linked list with a cycle present.
This was asked in one of interviews I recently attended and I was not able to prove it comprehensively to myself that whether the above is possible. Any help appreciated.
Suppose there is a loop, say of length
L.Easy case first
To make it easier, first consider the case where the two particles entire loop at the same time. These particles are at the same position whenever
n*A = n*B (mod L)for some positive integern, which is the number of steps until they meet again. Takingn=Lgives one solution (though there may be a smaller solution). So afterLunits of time, particleAhas madeAtrips around the loop to be back at the beginning and particleBhas madeBtrips around the loop to be back at the beginning, where they happily collide.General Case
Now what happens when they do not enter the loop at the same time? Let
Abe the slower particle, i.e.A<B, and supposeAenters the loop at timem, and let’s call the position at whichAenters the loop0(since they’re in the loop, they can never leave it, so I’m just renaming positions by subtractingA*m, the distanceAhas traveled aftermtime units). Then, at that time,Bis already at positionm*(B-A)(it’s real position aftermtime units isB*mand it’s renamed position is thereforeB*m-A*m). Then we need to show that there is a timensuch thatn*A = n*B+m*(B-A) (mod L). That is, we need a solution to the modular equationTaking
n = k*L-mforklarge enough thatk*L>mdoes the trick, though again, there may be a smaller solution.Therefore, yes, they always meet.