Given the head of a linked list that may contain a loop. A loop means that the last node of the linked list is connected back to a node in the same list. The task is to remove the loop from the linked list (if it exists).
[Naive Approach] Detect and Remove Loop using Hashing - O(n) Time and O(n) Space
The idea is to start traversing the Linked List from head node and while traversing insert each node into the HashSet. Also, maintain a prev pointer which points to the previous node of the current node. If there is a loop present in the Linked List, there will be a node which will be already present in the hash set.
If there is a node which is already present in the HashSet, then update the next pointer of prev to NULL to remove the loop from the linked list.
else, if there is no node which is already present in the HashSet , then there is no loop in the linked list.
Output
1 3 4
Time Complexity: O(n), Where n is the number of nodes in the linked list. Auxiliary Space: O(n), Where n is the number of nodes in the linked list(due to hashing).
[Efficient Approach] Using Floyd's Cycle Detection Algorithm - O(n) Time and O(1) Space
Use two pointers, slow and fast and initialize them with the head of the linked list.
Move the fast pointer forward by two nodes and move the slow pointer forward by one node.
If the slow and fast pointer points to the same node, loop is found.
Else if the fast pointer reaches NULL, then no loop is found.
Else repeat the above steps till we reach the end of the linked list or a loop is found.
2. Remove Loop in Linked List (if any):
The idea is similar to finding the starting node of Loop in a Linked List. For this, we will point the slow pointer to head node and fast pointer will remain at its position. Both slow and fast pointers move one step ahead until fast->next is not equals to slow->next. When slow->next equals to fast->next we can easily point fast->next to NULL to remove the loop.
Output
1 3 4
Time Complexity: O(n), where n is the number of nodes in the Linked List Auxiliary Space: O(1)