Home

[This page is auto-generated; please prefer to read the article’s PDF Form.]



Cycle Detection: Floyd’s Algorithm

Nitin Verma

August 19, 2021

Let f be a function from a finite set S to the same set. So, for any element e0 of S, each of the elements obtained as f(e0),f(f(e0)),f(f(f(e0))), will also belong to S. For any i 0, let ei denote the element obtained after applying function f over e0 i times. That is,

                                  i
ei = f (f (...{i times } f (e0) ...)) = f (e0)

Clearly, all ei are in S. Since S is a finite set, not all ei can be distinct. Say, e0,e1,e2,,eu are all distinct for some u, and eu+1 = el for some l u. Due to this, eu+2 = f(eu+1) = f(el) = el+1, similarly eu+3 = el+2, and likewise all subsequent ei will belong to this “cycle”: el,el+1,,eu.

We will denote by n (n 1) the number of elements in this cycle: n = ul + 1, and so u = l + n1. The following diagram depicts this situation; each arrow indicates application of function f:

e0 → e1 → e2 → ...→  el → el+1 → el+2 → ...→ el+n −1
                                                |
                     ↑---------------------------

Since any ei (including i l + n) equals one of the above l + n distinct elements, it can be associated with one particular index among these l + n elements’ indices. We will refer to it as the “index of ei”. For i < l, the index of ei is simply i, and for i l, the index is:

l + (i− l) mod n
(1)

Given the initial element e0 and function f, we need to find l and n. In this article, we discuss the Floyd’s Cycle Detection Algorithm for this problem, named after R. W. Floyd ([1]: section 3.1, exercise 6). It is also called Tortoise-Hare Algorithm [2].

Many other situations can transform to this generic problem, including a well-known problem of how we can detect cycle in a linked-list (described later in section “Detecting Cycle in a Linked-List”).

[Next]