Warning: Use of undefined constant fixed - assumed 'fixed' (this will throw an Error in a future version of PHP) in /home/webtro13/domains/farenda.com/public_html/wp-content/themes/moments/header.php on line 65
class="header_container_flat">

Cycle detection in linked list

The idea behind Floyd’s algorithm is straightforward. We go through the list in two speeds: by 1 node (slow as a tortoise), and jump every 2 nodes (jumps like a hare). Here’s the thing: when there is a cycle, the hare will eventually meet the tortoise. Let’s implement that.

Why it works

After finding the cycle, the hare and the tortoise are at the same position in the cycle – the meeting point. Now we can define a few things:

x – distance before entering the cycle.

y – distance in the loop before the meeting point.

z – distance between the meeting point and the beginning/end of the loop.

Having defined these variables we can calculate the following things:

tortoise distance before the meeting point = x + y

hare distance before the meeting = (x + y + z) + y = x + 2y + z Hare went through x, was in the loop sooner, therefore had to go through distance y once, then close the loop with distance z, and then again had to go through distance y to the meeting point.

Now, if the tortoise is at the beginning of the list, and the hare is at the meeting point. How can we know that advancing both at the same speed will make them meet at the beginning of the cycle? The distance covered by hare is twice of that covered by the tortoise. Therefore we can define the following equation: