Hello students, welcome back, so here in this problem we are given a linked list basically and we need to find if there is a cycle in the list or not i.e. if the last node of the list points to one of its previous nodes.
Let's understand this with the example
Here, in this list, the last node points to the second node so, we have a cycle here, to detect it, the simplest approach is to keep track of the visited nodes in a hashmap i.e. use a map<ListNode*, int> type where for each node we store 1 if it is visited else 0.
Now, while traversing we come across a node that is already visited, then there is a cycle like in the above example 2 will be revisited.
// using MAP
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL)
return false;
unordered_map<ListNode*,int> map;
while(head!=NULL){
if(map.count(head)>0)
return true;
else
map[head]=1;
head=head->next;
}
return false;
}
};
The time complexity for this approach is O(N) as we are traversing the list exactly once while space complexity is O(N) as we are using a hashmap container.
Optimal Approach: Floyd Algorithm:
Now, I want to optimize the space complexity for the given linked list. To do so we shall be using Floyd Cycle Detection Algorithm.
In this algorithm, we use two pointers, fast and slow both initialized to the first node of the linked list.
Now, move the fast pointer by 2 steps and the slow pointer by one step parallely till they meet at a certain point, if they meet then we return true otherwise we don't have a cycle in the list so return false.
Let's see the implementation.
//Floyd Algorithm
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL || head->next==NULL)
return false;
ListNode* slow=head;
ListNode* fast=head;
while(fast!=NULL && fast->next!=NULL){
slow=slow->next;
fast=fast->next->next;
if(fast==slow)
return true;
}
return false;
}
};
The Proof for this algorithm is given here (Optional) https://cs.stackexchange.com/questions/10360/floyds-cycle-detection-algorithm-determining-the-starting-point-of-cycle
Let's discuss the time and space complexity for the given implementation.
We can see that we are traversing the linked list in a linear fashion exactly once hence, O(N) time complexity, while the space complexity is O(1) as we are not using any extra auxiliary space here.
that's all I have got for this problem, feel free to ask your doubts :)
Hope to see you in the next problem.