Given a linked list containing a cycle, return the starting node of the cycle without modifying the list. Report if there are no cycles in the linked list.

For instance, the linked list below has a cycle, and the cycle begins at node 2.

Floyd’s Cycle Detection Algorithm

 
We can easily identify if the linked list contains a cycle or not using Floyd’s cycle detection algorithm. The idea is to take two pointers, slow and fast, where the fast pointer moves through the list at double the speed as the slow pointer. The cycle is present in the list if both pointers cross at any node in the linked list. In order to locate the start of the cycle in the linked list, we can take another pointer that begins at the head node and move it along with the slow pointer (from its last location) at a normal pace. The cycle in the linked list begins at the position where this pointer and the slow pointer intersect.

Following is the C++, Java, and Python implementation based on the idea:

C++


Download  Run Code

Output:

Cycle found starting from node 2

Java


Download  Run Code

Output:

Cycle found starting from node 2

Python


Download  Run Code

Output:

Cycle found starting from node 2

The time complexity of the above solution is O(n) and works in O(1) space, where n is the total number of nodes in the linked list.