1

Givens. I understand Floyd's algorithm can determine the length $\lambda$ of the loop and the length $m$ of the tail. The hare will not necessarily catch the tortoise on the first cycle, but it is guaranteed to catch it after a number $k$ of cycles, where $k$ is a natural number.

Question. Given I know these facts, how can I deduce the worst case complexity of the algorithm?

An answer that seems fallacious. For the tortoise and the hare to meet, they both need to be in the cycle. This will occur certainly after $\mu + \lambda$ iterations. Once the tortoise is in the cycle, the distance between the tortoise and the hare diminishes by one at each iteration. Yuval Filmus' answer shows that they meet in the cycle in an index that's a multiple of $\lambda$. Therefore, after they're both in the cycle, after $\lambda$ iterations (in the worst case) they must have reduced their distance to zero --- because the largest distance between them in the cycle is $\lambda$. But how do I know the hare didn't jump the tortoise? This argument doesn't seem very good.

R. Chopin
  • 237
  • 1
  • 9

2 Answers2

2

In this answer, I show that $x_i = x_{2i}$ iff $i \geq \mu$ and $i$ is a multiple of $\lambda$. In particular, this will happen for some index $i$ in the range $\{\mu,\ldots,\mu+\lambda-1\}$. This shows that the algorithm runs in time $O(\mu + \lambda)$.

Yuval Filmus
  • 280,205
  • 27
  • 317
  • 514
2

(Adapted from a StackOverflow answer.)

The tortoise arrives at the loop on iteration $\mu$. Since the hare moves faster, it is already in the loop. From the hare's perspective, the tortoise is now some distance ahead of it, and that distance is certainly less than $\lambda$.

Since the hare gets one step closer to the tortoise on each iteration, it will catch up in less than $\lambda$ more iterations, for a worst-case total of $\mu+\lambda-1$.

It is impossible for the hare to pass the tortoise without them both occupying the same spot. Suppose the hare is one step behind. Then, on the next iteration they will be on the same spot. If, on the other hand, the hare is more than one step behind, it will still be behind after the next iteration because it only gets one step closer.

Yuval's proof is much more precise and mathematical, and is certainly correct. But this simple explanation seems to have a certain intuitive value.

rici
  • 12,150
  • 22
  • 40