Are you in a cycle?

ogzhncrt
2 min readNov 17, 2021

We all know the story of the tortoise and hare. Well, from a different point of view, can these two animals be given more responsibility? —We’re not burdening the animals enough already.

With this point of view, which was put forward by Computer Scientist Robert W. Floyd in his article titled Nondeterministic Algorithms in 1967, it is possible to solve whether you are in a cycle or not in linear time.

For those who are interested in computer science, you can find a very well-prepared article here by Tu Vo; https://medium.com/@tuvo1106/the-tortoise-and-the-hare-floyds-algorithm-87badf5f7d41

And by quoting the pseudo-code, I can share it as follows;

1.Initialize two pointers (tortoise and hare) that both point to the head of the linked list

2. Loop as long as the hare does not reach null

3. Set tortoise to next node

4. Set hare to next, next node

5. If they are at the same node, reset the tortoise back to the head.

6. Have both tortoise and hare both move one node at a time until they meet again

7. Return the node in which they meet

8. Else, if the hare reaches null, then return null

Using the pseudocode above, it is possible to detect this in a time of about the length of the cycle ( O(n) ). Without using this algorithm, you would have to use methods that would take longer than linear time, such as O(n²) or O(n+m) to detect whether you are in a cycle or not. To give a different perspective to the above algorithm; You can tell if you’re in a cycle or not as long as hares going faster than you give you accurate information about what’s in front of you.

Sometimes you don’t need to be the fastest or it’s not enough, working with hares you believe to be correct in your business life and listening to them shortens the path for you. It clarifies whether you are in the right cycle or not for your career.

Lone hares are just as difficult as the tortoise to quickly detect that they’re on the right cycle and need tortoises that provide accurate information to them.

--

--

ogzhncrt
0 Followers

Versatile Full-Stack Developer