Given the head of a singly linked list, determine the length of the cycle (loop) if one exists. A cycle occurs when a node's next pointer points to a previously visited node in the list. If no cycle is present, return 0.
Examples:
Input:
Output: 3 Explanation: There exists a loop in the linked list and the length of the loop is 3.
Input:
Output: 0 Explanation: There is no loop present in the Linked List.
[Naive Approach] Using Set - O(n) Time and O(n) Space
The idea is to maintain a set to keep track of visited nodes so far. If the node is not present in set we will insert and move to another node, else we will maintain a counter from that node and will start traversing until we reach to it again by incrementing the counter variable every time.
C++
#include<iostream>#include<unordered_set>usingnamespacestd;// Node structureclassNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};intlengthOfLoop(Node*head){unordered_set<Node*>visited;Node*current=head;intcount=0;while(current!=nullptr){// if the node is already visited, // it means there is a loopif(visited.find(current)!=visited.end()){Node*startOfLoop=current;do{count++;current=current->next;}while(current!=startOfLoop);returncount;}// mark the current node as visitedvisited.insert(current);// move to the next nodecurrent=current->next;}return0;}intmain(){Node*head=newNode(25);head->next=newNode(14);head->next->next=newNode(19);head->next->next->next=newNode(33);head->next->next->next->next=newNode(10);head->next->next->next->next->next=head->next->next;cout<<lengthOfLoop(head)<<endl;return0;}
Java
importjava.util.HashSet;// Node structureclassNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{staticintlengthOfLoop(Nodehead){HashSet<Node>visited=newHashSet<>();Nodecurrent=head;intcount=0;while(current!=null){// if the node is already visited, // it means there is a loopif(visited.contains(current)){NodestartOfLoop=current;do{count++;current=current.next;}while(current!=startOfLoop);returncount;}// mark the current node as visitedvisited.add(current);// move to the next nodecurrent=current.next;}return0;}publicstaticvoidmain(String[]args){Nodehead=newNode(25);head.next=newNode(14);head.next.next=newNode(19);head.next.next.next=newNode(33);head.next.next.next.next=newNode(10);head.next.next.next.next.next=head.next.next;System.out.println(lengthOfLoop(head));}}
Python
# Node structureclassNode:def__init__(self,x):self.data=xself.next=NonedeflengthOfLoop(head):visited=set()current=headcount=0whilecurrentisnotNone:# if the node is already visited, # it means there is a loopifcurrentinvisited:startOfLoop=currentwhileTrue:count+=1current=current.nextifcurrent==startOfLoop:breakreturncount# mark the current node as visitedvisited.add(current)# move to the next nodecurrent=current.nextreturn0if__name__=="__main__":head=Node(25)head.next=Node(14)head.next.next=Node(19)head.next.next.next=Node(33)head.next.next.next.next=Node(10)head.next.next.next.next.next=head.next.nextprint(lengthOfLoop(head))
C#
usingSystem;usingSystem.Collections.Generic;// Node structureclassNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{staticintlengthOfLoop(Nodehead){HashSet<Node>visited=newHashSet<Node>();Nodecurrent=head;intcount=0;while(current!=null){// if the node is already visited, // it means there is a loopif(visited.Contains(current)){NodestartOfLoop=current;do{count++;current=current.next;}while(current!=startOfLoop);returncount;}// mark the current node as visitedvisited.Add(current);// move to the next nodecurrent=current.next;}return0;}publicstaticvoidMain(string[]args){Nodehead=newNode(25);head.next=newNode(14);head.next.next=newNode(19);head.next.next.next=newNode(33);head.next.next.next.next=newNode(10);head.next.next.next.next.next=head.next.next;Console.WriteLine(lengthOfLoop(head));}}
JavaScript
// Node structureclassNode{constructor(x){this.data=x;this.next=null;}}functionlengthOfLoop(head){constvisited=newSet();letcurrent=head;letcount=0;while(current!==null){// if the node is already visited, // it means there is a loopif(visited.has(current)){conststartOfLoop=current;do{count++;current=current.next;}while(current!==startOfLoop);returncount;}// mark the current node as visitedvisited.add(current);// move to the next nodecurrent=current.next;}return0;}// Driver Codelethead=newNode(25);head.next=newNode(14);head.next.next=newNode(19);head.next.next.next=newNode(33);head.next.next.next.next=newNode(10);head.next.next.next.next.next=head.next.next;console.log(lengthOfLoop(head));
Output
3
[Expected Approach] Using Floyd’s Cycle Detection Algorithm - O(n) Time and O(1) Space
Use a fast and slow pointer pointing to head of linked list.
move fast pointer to fast->next->next and slow pointer to slow->next.
If a common meeting point exists between the slow and fast pointers, it confirms the presence of a loop.
Once the loop is detected, we start counting the number of nodes in the loop by initializing a counter and traversing the loop starting from the meeting point.
If no meeting point is found, it means there is no loop, so we return 0.
C++
#include<iostream>usingnamespacestd;// Node structureclassNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Returns count of nodes present in loop.intcountNodes(Node*node){intres=1;Node*curr=node;while(curr->next!=node){res++;curr=curr->next;}returnres;}// Detects and Counts nodes in loopintlengthOfLoop(Node*head){Node*slow=head,*fast=head;while(slow!=nullptr&&fast!=nullptr&&fast->next!=nullptr){slow=slow->next;fast=fast->next->next;// If slow and fast meet at// some point then there is a loopif(slow==fast)returncountNodes(slow);}return0;}intmain(){Node*head=newNode(25);head->next=newNode(14);head->next->next=newNode(19);head->next->next->next=newNode(33);head->next->next->next->next=newNode(10);head->next->next->next->next->next=head->next->next;cout<<lengthOfLoop(head)<<endl;return0;}
Java
// Node structureclassNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{// Returns count of nodes present in loop.staticintcountNodes(Nodenode){intres=1;Nodecurr=node;while(curr.next!=node){res++;curr=curr.next;}returnres;}// Detects and Counts nodes in loopstaticintlengthOfLoop(Nodehead){Nodeslow=head,fast=head;while(slow!=null&&fast!=null&&fast.next!=null){slow=slow.next;fast=fast.next.next;// if slow and fast meet at// some point then there is a loopif(slow==fast)returncountNodes(slow);}return0;}publicstaticvoidmain(String[]args){Nodehead=newNode(25);head.next=newNode(14);head.next.next=newNode(19);head.next.next.next=newNode(33);head.next.next.next.next=newNode(10);head.next.next.next.next.next=head.next.next;System.out.println(lengthOfLoop(head));}}
Python
# Node structureclassNode:def__init__(self,x):self.data=xself.next=None# Returns count of nodes present in loop.defcountNodes(node):res=1curr=nodewhilecurr.next!=node:res+=1curr=curr.nextreturnres# Detects and Counts nodes in loopdeflengthOfLoop(head):slow=headfast=headwhileslowisnotNoneandfastisnotNone \
andfast.nextisnotNone:slow=slow.nextfast=fast.next.next# if slow and fast meet at# some point then there is a loopifslow==fast:returncountNodes(slow)return0if__name__=="__main__":head=Node(25)head.next=Node(14)head.next.next=Node(19)head.next.next.next=Node(33)head.next.next.next.next=Node(10)head.next.next.next.next.next=head.next.nextprint(lengthOfLoop(head))
C#
usingSystem;// Node structureclassNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Returns count of nodes present in loop.publicstaticintcountNodes(Nodenode){intres=1;Nodecurr=node;while(curr.next!=node){res++;curr=curr.next;}returnres;}// Detects and Counts nodes in looppublicstaticintlengthOfLoop(Nodehead){Nodeslow=head,fast=head;while(slow!=null&&fast!=null&&fast.next!=null){slow=slow.next;fast=fast.next.next;// if slow and fast meet at// some point then there is a loopif(slow==fast)returncountNodes(slow);}return0;}publicstaticvoidMain(string[]args){Nodehead=newNode(25);head.next=newNode(14);head.next.next=newNode(19);head.next.next.next=newNode(33);head.next.next.next.next=newNode(10);head.next.next.next.next.next=head.next.next;Console.WriteLine(lengthOfLoop(head));}}
JavaScript
// Node structureclassNode{constructor(x){this.data=x;this.next=null;}}// Returns count of nodes present in loop.functioncountNodes(node){letres=1;letcurr=node;while(curr.next!==node){res++;curr=curr.next;}returnres;}// Detects and Counts nodes in loopfunctionlengthOfLoop(head){letslow=head,fast=head;while(slow!==null&&fast!==null&&fast.next!==null){slow=slow.next;fast=fast.next.next;// if slow and fast meet at// some point then there is a loopif(slow===fast)returncountNodes(slow);}return0;}// Driver Codelethead=newNode(25);head.next=newNode(14);head.next.next=newNode(19);head.next.next.next=newNode(33);head.next.next.next.next=newNode(10);head.next.next.next.next.next=head.next.next;console.log(lengthOfLoop(head));