Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cycle detection in a linked list : Exhaustive theory

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.

like image 230
bragboy Avatar asked Dec 17 '11 07:12

bragboy


1 Answers

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 integer n, which is the number of steps until they meet again. Taking n=L gives one solution (though there may be a smaller solution). So after L units of time, particle A has made A trips around the loop to be back at the beginning and particle B has made B trips 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 A be the slower particle, i.e. A<B, and suppose A enters the loop at time m, and let's call the position at which A enters the loop 0 (since they're in the loop, they can never leave it, so I'm just renaming positions by subtracting A*m, the distance A has traveled after m time units). Then, at that time, B is already at position m*(B-A) (it's real position after m time units is B*m and it's renamed position is therefore B*m-A*m). Then we need to show that there is a time n such that n*A = n*B+m*(B-A) (mod L). That is, we need a solution to the modular equation

(n+m) * (A-B) = 0 (mod L)

Taking n = k*L-m for k large enough that k*L>m does the trick, though again, there may be a smaller solution.

Therefore, yes, they always meet.

like image 51
PengOne Avatar answered Oct 10 '22 17:10

PengOne