![]() |
VOOZH | about |
Given a linked list, check if the linked list has loop or not. Below diagram shows a linked list with a loop.
The following are different ways of doing this.
Hashing Approach:
Traverse the list one by one and keep putting the node addresses in a Hash Table. At any point, if NULL is reached then return false, and if the next of the current nodes points to any of the previously stored nodes in Hash then return true.
Loop found
Complexity Analysis:
: This problem can be solved without hashmap by modifying the linked list data structure.
Approach: This solution requires modifications to the basic linked list data structure.
Loop found
Complexity Analysis:
: Floyd's Cycle-Finding Algorithm
Approach: This is the fastest method and has been described below:
The below image shows how the detectloop function works in the code:
Implementation of Floyd's Cycle-Finding Algorithm:
Loop found
Complexity Analysis:
How does above algorithm work?
Please See : How does Floyd’s slow and fast pointers approach work?
https://www.youtube.com/watch?v=Aup0kOWoMVg
: Marking visited nodes without modifying the linked list data structure
In this method, a temporary node is created. The next pointer of each node that is traversed is made to point to this temporary node. This way we are using the next pointer of a node as a flag to indicate whether the node has been traversed or not. Every node is checked to see if the next is pointing to a temporary node or not. In the case of the first node of the loop, the second time we traverse it this condition will be true, hence we find that loop exists. If we come across a node that points to null then the loop doesn’t exist.
Below is the implementation of the above approach:
Loop Found
Complexity Analysis:
In this method, two pointers are created, first (always points to head) and last. Each time the last pointer moves we calculate no of nodes in between first and last and check whether the current no of nodes > previous no of nodes, if yes we proceed by moving last pointer else it means we've reached the end of the loop, so we return output accordingly.
Loop Found
Complexity Analysis:
Follow the code given below for a better understanding:
1
Time Complexity: O(N)
Auxiliary Space: O(1)
Please refer complete article on Detect loop in a linked list for more details!