Site icon Study Algorithms

Find cycle in a linked list. (Method 1)

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


Output: 0

We are given a linked list which may or may not have a loop. A loop in a linked list means that if we keep doing a next, we will never reach null. Thus, we can be clear of a fact that if we reach null, then the list does not have a loop.

So how do we detect if there is a loop in the linked list. One method that immediately comes to our mind is that if a value is encountered twice, there may be a chance that the linked list has a loop. Thus, we can use Sets to keep track of all the values traversed.

Algorithm

The algorithm necessarily terminates for any list with a finite number of nodes, as the domain of input lists can be divided into two categories: cyclic and acyclic lists. An acyclic list resembles a null-terminated chain of nodes, while a cyclic list can be thought of as an acyclic list with the final null replaced by a reference to some previous node. If the while loop terminates, we return null, as we have traversed the entire list without encountering a duplicate reference. In this case, the list is acyclic. For a cyclic list, the while loop will never terminate, but at some point the if condition will be satisfied and cause the function to return.

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

public class Solution {

    public ListNode detectCycle(ListNode head) {

        Set<ListNode> visited = new HashSet<ListNode>();
        ListNode node = head;

        // Traverse the list
        while (node != null) {

            // If the node is already present in the Set
            // this is a loop and we need to return it.
            if (visited.contains(node)) {
                return node;
            }

            visited.add(node);
            node = node.next;
        }
        // No loop found
        return null;
    }
}
Code language: Java (java)

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

A sample problem can be found here.

A method with constant space can be found here.

Find cycle in a Linked List (Method 2)

Exit mobile version