linked-list

Intuition behind Tortoise and Hare algorithm


I can write code using the Tortoise and Hare algorithm, and it works. But it doesn't make intuitive sense to me. It feels like it could break down for the right cycle length and hare step size.

Are there alternative explanations to help me understand?


Solution

  • If there is a cycle, you can think of it as an infinitely repeating number line.

    At the start of the Tortoise and Hare algorithm, we place the hare one node ahead of the tortoise. But once they enter the cycle, you can think of the hare being positioned behind the tortoise.

    The typical steps for the tortoise and hare are 1 and 2, respectively. And no matter how far behind the hare is, it reduces down to two options - 1 step back, or 2 steps back.

    If the hare is 1 step back, it will meet with the tortoise on the next step. Tortoise moves 1, Hare moves 2.

    If the hare is 2 steps back, the tortoise will move forward 1, and the hare will move forward 2. Now, the hare is only one step back, and they'll meet on the next step.

    To me this makes sense, and it appears to generalize to any size step the hare takes. The key insight for me was changing my mental approach from a cycle to an infinite, repeating number line.