Floyd’s Cycle Detection

There is a famous algorithm called Floyd’s Cycle Detection Algorithm aka Tortoise and Hare Algorithm. It is used to detect a cycles in a list.

The tortoise is the slow pointer and the hare as fast pointer. The hare will travel in strides ot 2 while the tortoise will travel in stride of 1.

Image the following senario a linked list with a cycle.

Cycles

Some notation that we wiil use: mm is the distance from the start of the list to the start of the cycle, PP is the length of the cycle, and kk is the distance from the start of the cycle to the point where the hare and tortoise meet.

If one reached the end of the list, there is no cycles. If the two meet then there are 2 senarios that can happen:

{i=m+k+aPaZj=m+k+bPbZ \Rightarrow \left\{ \begin{array}{ll} i=m+k+aP & \exist a \in \mathbb{Z} \\ j=m+k+bP & \exist b \in \mathbb{Z} \\ \end{array} \right.

a:=total loops the tortoise traveledb:=total loops the hare traveledi:=total distance tortoise traveledj:=total distance hare traveled\begin{aligned} a &:= \text{total loops the tortoise traveled} \\ b &:= \text{total loops the hare traveled} \\ i &:= \text{total distance tortoise traveled} \\ j &:= \text{total distance hare traveled} \end{aligned}

Since the hare is traveling at twice the speed of the tortoise, if the two ever meet, the hare has traveled twice the distance. Therefore:

j=2ij = 2i

With some simple algebra

m+k+bP=2((m+k)+aP)m+k=bP2aPi=bP2aP+aP=bPaP\begin{aligned} m+k + bP &= 2((m+k) + aP) \\ m+k &= bP – 2aP \\ \Rightarrow i &= bP – 2aP + aP \\ &= bP – aP \end{aligned}

The next step is to put the hare at the beginning of the cycles, but this time have both the tortoise and the hare take strides of 1. The point at which the 2 meet will be the start of the cycle.

Since the tortoise is currently at (ba)P(b-a)P when the hare travels mm steps:

  1. The hare is at mm
  2. The tortoise is at (ba)P+m(b - a)P + m

We can rearrange the tortoise to have traveled m+(ba)Pm + (b - a)P or taking mm step then a integer multiple of PP. Since there exits a cycles, traveling an integer multiple of PP around the cycles will land you at the beginning of the cycle.