Site icon Study Algorithms

Find cycle in a linked list. (Method 2)

Question: Given a linked list, return the node where the cycle begins. If there is no cycle, return null.



Output: 0

The easier method to find the cycle has been discussed in this post.

This method is based upon the idea of a circular race track. If there is a slow runner and a fast runner, eventually the fast runner will catch up the slow runner from behind. A similar analogy can be applied to a tortoise and a hare and hence the method is also called Tortoise and Hare method or the Floyd-Warshal algorithm.

The method is divided into 2 steps.

STEP 1: Determine if there is a loop.
The first phase/step of this method is to determine if there is actually any loop in the Linked List. If no loop is found, then we need to directly return null.

STEP 2: Find the loop.

To have a better understanding of why this method works, have a look at the following image.

We know that speed of hare is double the speed of tortoise.
Let us look at a little math now:-

​2 * distance(tortoise)​ ​​​​= distance(hare)​
2 * (F + a) = F + a + b + a​
​2F + 2a = F + 2a + b
​F​ = b​​

Hence POINT 2 is the point where loop starts.

The source-code for the above algorithm is given below.

// Template for a linked list node
class ListNode {
    int value;
    ListNode next;
}

public class Solution {

    private ListNode getIntersect(ListNode head) {
        ListNode tortoise = head;
        ListNode hare = head;

        // A fast pointer will either loop around a cycle and meet the slow
        // pointer or reach the `null` at the end of a non-cyclic list.
        while (hare != null && hare.next != null) {
            tortoise = tortoise.next;
            hare = hare.next.next;
            if (tortoise == hare) {
                return tortoise;
            }
        }

        return null;
    }

    public ListNode detectCycle(ListNode head) {
        if (head == null) {
            return null;
        }

        // If there is a cycle, the fast/slow pointers will intersect at some
        // node. Otherwise, there is no cycle, so we cannot find an entrance to
        // a cycle.
        ListNode intersect = getIntersect(head);
        if (intersect == null) {
            return null;
        }

        // To find the entrance to the cycle, we have two pointers traverse at
        // the same speed -- one from the front of the list, and the other from
        // the point of intersection.
        ListNode ptr1 = head;
        ListNode ptr2 = intersect;
        while (ptr1 != ptr2) {
            ptr1 = ptr1.next;
            ptr2 = ptr2.next;
        }

        return ptr1;
    }
}
Code language: Java (java)

Time Complexity: O(n)
Space Complexity: O(1)

A sample problem can be found here.

Exit mobile version