Cycle/Loop Detection in Linked Lists

 Alright so we are back with another agonizing task at our hand! This one is similar to removing loop from our linked list albeit simpler, We just need to return true or false based on whether a loop exists in the linked list or not. 

Example- 1->2->3->1->NULL

Let's code a function to detect this-

bool has_cycle(SinglyLinkedListNode* head) {
    if(head==NULL)
    {
        return false;
    }
    SinglyLinkedListNode* slowptr=head;
    SinglyLinkedListNode* fastptr=head;
    while(fastptr!=NULL && fastptr->next!=NULL)
    {
        slowptr=slowptr->next;
        fastptr=fastptr->next->next;
        if(fastptr==slowptr)
        {
            return true;
        }
    }
    return false;
}

So here we have used Floyd's cycle detection algorithm which in basic terms means - 

A rabbit will run twice as fast as a tortoise in a circular track, and considering this rabbit isn't lazy, there will come a point where the two animals meet again

Now that we have vaguely mentioned what this means, let's understand the function itself

Steps- 

  1. We create 2 pointers- fast and slow and set each value to the head
  2. Now we iterate a loop using fast pointer, the condition set as the current as well as the next value of the fast pointer doesn't reach NULL
  3. We make the slow pointer move 1 place ahead and fast pointer move 2 places ahead
  4. We then create an if condition to check in case throughout the loop the 2 (slow and fast) ever become equal again, and if they do- then we have a loop at our hands!
  5. return true or false based on this.  
As always, That's what i coded!

Popular posts from this blog

Finding the Subarrays (Hackerearth)

Palindrome Index (Hackerrank)

Sherlock and Array (Hackerrank)