This post will detect cycles in a linked list using hashing and Floyd’s cycle detection algorithm.

For example, the following linked list has a cycle in it:

Floyd’s Cycle Detection Algorithm

Practice this problem

1. Using Hashing

A simple solution is to use hashing. The idea is to traverse the given list and insert each encountered node into a set. If the current node already presents in the set (i.e., it is seen before), that means a cycle is present in the list.

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

Cycle Found

Java


Download  Run Code

Output:

Cycle Found

Python


Download  Run Code

Output:

Cycle Found

The time complexity of the above solution is O(n), where n is the total number of nodes in the linked list. The auxiliary space required by the program is O(n).

2. Floyd’s Cycle Detection Algorithm

Floyd’s cycle detection algorithm is a pointer algorithm that uses only two pointers, which move through the sequence at different speeds. The idea is to move the fast pointer twice as quickly as the slow pointer, and the distance between them increases by one at each step. If we both meet at some point, we have found a cycle in the list; otherwise, no cycle is present if the end of the list is reached. It is also called the “tortoise and the hare algorithm”.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

Cycle Found

Java


Download  Run Code

Output:

Cycle Found

Python


Download  Run Code

Output:

Cycle Found

The time complexity of the above solution is O(n), where n is the total number of nodes in the linked list, and doesn’t require any extra space.