Given the head of a linked list. The task is to find if a loop exists in the linked list if yes then return the length of the loop in the linked list else return 0.
Examples:
Input: linked list =
Output: 4
Explanation: The loop is present in the below-linked list and the length of the loop is 4.ÂInput: linked list = 4 -> 3 -> 7 -> 9 -> 2
Output: 0
Approach: Below is the idea to solve the problem:
Floyd’s Cycle detection algorithm terminates when fast and slow pointers meet at a common point. It is also known that this common point is one of the loop nodes. Store the address of this common point in a pointer variable ptr. Then initialize a counter with 1 and start from the common point and keeps on visiting the next node and increasing the counter till the common pointer is reached again. At that point, the value of the counter will be equal to the length of the loop.
Follow the below steps to implement the idea:
- Find the common point in the loop by using the Floyd’s Cycle detection algorithm
- Store the pointer in a temporary variable and keep a count = 0
- Traverse the linked list until the same node is reached again and increase the count while moving to next node.
- Print the count as length of loop
Below is the implementation of the above approach:
C++
// C++ program to count number of nodes// in loop in a linked list if loop is// present#include <bits/stdc++.h>using namespace std;Â
/* Link list node */struct Node {Â Â Â Â int data;Â Â Â Â struct Node* next;};Â
// Returns count of nodes present in loop.int countNodes(struct Node* n){Â Â Â Â int res = 1;Â Â Â Â struct Node* temp = n;Â Â Â Â while (temp->next != n) {Â Â Â Â Â Â Â Â res++;Â Â Â Â Â Â Â Â temp = temp->next;Â Â Â Â }Â Â Â Â return res;}Â
/* This function detects and counts loop   nodes in the list. If loop is not there   then returns 0 */int countNodesinLoop(struct Node* list){    struct Node *slow_p = list, *fast_p = list;Â
    while (slow_p && fast_p && fast_p->next) {        slow_p = slow_p->next;        fast_p = fast_p->next->next;Â
        /* If slow_p and fast_p meet at        some point then there is a loop */        if (slow_p == fast_p)            return countNodes(slow_p);    }Â
    /* Return 0 to indicate that       there is no loop*/    return 0;}Â
struct Node* newNode(int key){    struct Node* temp        = (struct Node*)malloc(sizeof(struct Node));    temp->data = key;    temp->next = NULL;    return temp;}Â
// Driver Codeint main(){Â Â Â Â struct Node* head = newNode(1);Â Â Â Â head->next = newNode(2);Â Â Â Â head->next->next = newNode(3);Â Â Â Â head->next->next->next = newNode(4);Â Â Â Â head->next->next->next->next = newNode(5);Â
    /* Create a loop for testing */    head->next->next->next->next->next = head->next;Â
    cout << countNodesinLoop(head) << endl;Â
    return 0;}Â
// This code is contributed by SHUBHAMSINGH10 |
C
// C program to count number of nodes// in loop in a linked list if loop is// present#include <stdio.h>#include <stdlib.h>Â
/* Link list node */struct Node {Â Â Â Â int data;Â Â Â Â struct Node* next;};Â
// Returns count of nodes present in loop.int countNodes(struct Node* n){Â Â Â Â int res = 1;Â Â Â Â struct Node* temp = n;Â Â Â Â while (temp->next != n) {Â Â Â Â Â Â Â Â res++;Â Â Â Â Â Â Â Â temp = temp->next;Â Â Â Â }Â Â Â Â return res;}Â
/* This function detects and counts loop   nodes in the list. If loop is not there   then returns 0 */int countNodesinLoop(struct Node* list){    struct Node *slow_p = list, *fast_p = list;Â
    while (slow_p && fast_p && fast_p->next) {        slow_p = slow_p->next;        fast_p = fast_p->next->next;Â
        /* If slow_p and fast_p meet at some point           then there is a loop */        if (slow_p == fast_p)            return countNodes(slow_p);    }Â
    /* Return 0 to indicate that there is no loop*/    return 0;}Â
struct Node* newNode(int key){    struct Node* temp        = (struct Node*)malloc(sizeof(struct Node));    temp->data = key;    temp->next = NULL;    return temp;}Â
/* Driver program to test above function*/int main(){Â Â Â Â struct Node* head = newNode(1);Â Â Â Â head->next = newNode(2);Â Â Â Â head->next->next = newNode(3);Â Â Â Â head->next->next->next = newNode(4);Â Â Â Â head->next->next->next->next = newNode(5);Â
    /* Create a loop for testing */    head->next->next->next->next->next = head->next;Â
    printf("%d \n", countNodesinLoop(head));Â
    return 0;} |
Java
// Java program to count number of nodes// in loop in a linked list if loop is// presentimport java.util.*;import java.io.*;Â
public class GFG {Â
    /* Link list node */    static class Node {        int data;        Node next;        Node(int data)        {            this.data = data;            next = null;        }    }Â
    // Returns count of nodes present in loop.    static int countNodes(Node n)    {        int res = 1;        Node temp = n;        while (temp.next != n) {            res++;            temp = temp.next;        }        return res;    }Â
    /* This function detects and counts loop    nodes in the list. If loop is not there    then returns 0 */    static int countNodesinLoop(Node list)    {        Node slow_p = list, fast_p = list;Â
        while (slow_p != null && fast_p != null               && fast_p.next != null) {            slow_p = slow_p.next;            fast_p = fast_p.next.next;Â
            /* If slow_p and fast_p meet at some point            then there is a loop */            if (slow_p == fast_p)                return countNodes(slow_p);        }Â
        /* Return 0 to indicate that there is no loop*/        return 0;    }Â
    static Node newNode(int key)    {        Node temp = new Node(key);Â
        return temp;    }Â
    /* Driver program to test above function*/    public static void main(String[] args)    {        Node head = newNode(1);        head.next = newNode(2);        head.next.next = newNode(3);        head.next.next.next = newNode(4);        head.next.next.next.next = newNode(5);Â
        /* Create a loop for testing */        head.next.next.next.next.next = head.next;Â
        System.out.println(countNodesinLoop(head));    }}// This code is contributed by inder_verma. |
Python3
# Python 3 program to find the number# of nodes in loop in a linked list# if loop is presentÂ
# Python Code to detect a loop and# find the length of the loop# Node defining classÂ
Â
class Node:Â
    # Function to make a node    def __init__(self, val):        self.val = val        self.next = NoneÂ
# Linked List defining and loop# length finding classÂ
Â
class LinkedList:Â
    # Function to initialize the    # head of the linked list    def __init__(self):        self.head = NoneÂ
    # Function to insert a new    # node at the end    def AddNode(self, val):        if self.head is None:            self.head = Node(val)        else:            curr = self.head            while(curr.next):                curr = curr.next            curr.next = Node(val)Â
    # Function to create a loop in the    # Linked List. This function creates    # a loop by connecting the last node    # to n^th node of the linked list,    # (counting first node as 1)    def CreateLoop(self, n):Â
        # LoopNode is the connecting node to        # the last node of linked list        LoopNode = self.head        for _ in range(1, n):            LoopNode = LoopNode.nextÂ
        # end is the last node of the Linked List        end = self.head        while(end.next):            end = end.nextÂ
        # Creating the loop        end.next = LoopNodeÂ
    # Function to detect the loop and return    # the length of the loop if the returned    # value is zero, that means that either    # the linked list is empty or the linked    # list doesn't have any loop    def detectLoop(self):Â
        # if linked list is empty then there        # is no loop, so return 0        if self.head is None:            return 0Â
        # Using Floyd’s Cycle-Finding        # Algorithm/ Slow-Fast Pointer Method        slow = self.head        fast = self.head        flag = 0 # to show that both slow and fast        # are at start of the Linked List        while(slow and slow.next and fast and              fast.next and fast.next.next):            if slow == fast and flag != 0:Â
                # Means loop is confirmed in the                # Linked List. Now slow and fast                # are both at the same node which                # is part of the loop                count = 1                slow = slow.next                while(slow != fast):                    slow = slow.next                    count += 1                return countÂ
            slow = slow.next            fast = fast.next.next            flag = 1        return 0 # No loopÂ
Â
# Setting up the code# Making a Linked List and adding the nodesmyLL = LinkedList()myLL.AddNode(1)myLL.AddNode(2)myLL.AddNode(3)myLL.AddNode(4)myLL.AddNode(5)Â
# Creating a loop in the linked List# Loop is created by connecting the# last node of linked list to n^th node# 1<= n <= len(LinkedList)myLL.CreateLoop(2)Â
# Checking for Loop in the Linked List# and printing the length of the looploopLength = myLL.detectLoop()if myLL.head is None:Â Â Â Â print("Linked list is empty")else:Â Â Â Â print(str(loopLength))Â
# This code is contributed by _Ashutosh |
C#
// C# program to count number of nodes// in loop in a linked list if loop is// presentusing System;Â
class GFG {Â
    /* Link list node */    class Node {        public int data;        public Node next;        public Node(int data)        {            this.data = data;            next = null;        }    }Â
    // Returns count of nodes present in loop.    static int countNodes(Node n)    {        int res = 1;        Node temp = n;        while (temp.next != n) {            res++;            temp = temp.next;        }        return res;    }Â
    /* This function detects and counts loop    nodes in the list. If loop is not there    then returns 0 */    static int countNodesinLoop(Node list)    {        Node slow_p = list, fast_p = list;Â
        while (slow_p != null && fast_p != null               && fast_p.next != null) {            slow_p = slow_p.next;            fast_p = fast_p.next.next;Â
            /* If slow_p and fast_p meet at some point            then there is a loop */            if (slow_p == fast_p)                return countNodes(slow_p);        }Â
        /* Return 0 to indicate that there is no loop*/        return 0;    }Â
    static Node newNode(int key)    {        Node temp = new Node(key);Â
        return temp;    }Â
    /* Driver code*/    public static void Main(String[] args)    {        Node head = newNode(1);        head.next = newNode(2);        head.next.next = newNode(3);        head.next.next.next = newNode(4);        head.next.next.next.next = newNode(5);Â
        /* Create a loop for testing */        head.next.next.next.next.next = head.next;Â
        Console.WriteLine(countNodesinLoop(head));    }}Â
// This code is contributed by Rajput-Ji |
Javascript
<script>// javascript program to count number of nodes // in loop in a linked list if loop is // present Â
    /* Link list node */class Node {    constructor(data) {        this.data = data;        this.next = null;    }}Â
    // Returns count of nodes present in loop.    function countNodes( n) {        var res = 1;         temp = n;        while (temp.next != n) {            res++;            temp = temp.next;        }        return res;    }Â
    /*     * This function detects and counts loop nodes in the list. If loop is not there     * in then returns 0     */    function countNodesinLoop( list) {        var slow_p = list, fast_p = list;Â
        while (slow_p != null && fast_p != null && fast_p.next != null) {            slow_p = slow_p.next;            fast_p = fast_p.next.next;Â
            /*             * If slow_p and fast_p meet at some point then there is a loop             */            if (slow_p == fast_p)                return countNodes(slow_p);        }Â
        /* Return 0 to indicate that there is no loop */        return 0;    }Â
    function newNode(key) {         temp = new Node(key);Â
        return temp;    }Â
    /* Driver program to test above function */              head = newNode(1);        head.next = newNode(2);        head.next.next = newNode(3);        head.next.next.next = newNode(4);        head.next.next.next.next = newNode(5);Â
        /* Create a loop for testing */        head.next.next.next.next.next = head.next;Â
        document.write(countNodesinLoop(head));Â
// This code contributed by gauravrajput1</script> |
4
Time complexity: O(N), Only one traversal of the linked list is needed.
Auxiliary Space: O(1), As no extra space is required.
Another Approach: Using Hash set (Unordered_set ) to keep the track of the visited nodes.
Algorithm steps:
- Initialize an empty hash set and a pointer
currentto the head of the linked list. - Traverse the linked list using
current:a. If thecurrentnode is already in the hash set, there is a loop:- Initialize a variable
countto 1 and set a pointerstartOfLoopto the current node. - Increment
countand movecurrentuntil it reachesstartOfLoopagain. - Return
count, which represents the number of nodes in the loop.
b. If the
currentnode is not in the hash set, mark it as visited by inserting it into the hash set and movecurrentto the next node. - Initialize a variable
- If the traversal ends without finding a loop (i.e.,
currentbecomes nullptr), return 0 to indicate that there is no loop in the linked list.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>using namespace std;Â
/* Link list node */struct Node {Â Â Â Â int data;Â Â Â Â struct Node* next;};Â
/* This function detects and counts loop   nodes in the list. If loop is not there   then returns 0 */int countNodesinLoop(struct Node* list){    unordered_set<struct Node*> visited;    struct Node* current = list;    int count = 0;Â
    while (current != nullptr) {        // If the node is already visited, it means there is a loop        if (visited.find(current) != visited.end()) {            struct Node* startOfLoop = current;            do {                count++;                current = current->next;            } while (current != startOfLoop);            return count;        }Â
        // Mark the current node as visited        visited.insert(current);Â
        // Move to the next node        current = current->next;    }Â
    /* Return 0 to indicate that       there is no loop*/    return 0;}Â
struct Node* newNode(int key){Â Â Â Â struct Node* temp = new struct Node;Â Â Â Â temp->data = key;Â Â Â Â temp->next = nullptr;Â Â Â Â return temp;}Â
// Driver Codeint main(){Â Â Â Â struct Node* head = newNode(1);Â Â Â Â head->next = newNode(2);Â Â Â Â head->next->next = newNode(3);Â Â Â Â head->next->next->next = newNode(4);Â Â Â Â head->next->next->next->next = newNode(5);Â
    /* Create a loop for testing */    head->next->next->next->next->next = head->next;Â
    cout << countNodesinLoop(head) << endl;Â
    return 0;} |
Python3
class ListNode:    def __init__(self, val=0, next=None):        self.val = val        self.next = nextÂ
def countNodesInLoop(head):    visited = set()    current = head    count = 0Â
    while current is not None:        # If the node is already visited, it means there is a loop        if current in visited:            start_of_loop = current            while True:                count += 1                current = current.next                if current == start_of_loop:                    break            return countÂ
        # Mark the current node as visited        visited.add(current)Â
        # Move to the next node        current = current.nextÂ
    # Return 0 to indicate that there is no loop    return 0Â
# Driver Codeif __name__ == "__main__":Â Â Â Â head = ListNode(1)Â Â Â Â head.next = ListNode(2)Â Â Â Â head.next.next = ListNode(3)Â Â Â Â head.next.next.next = ListNode(4)Â Â Â Â head.next.next.next.next = ListNode(5)Â
    # Create a loop for testing    head.next.next.next.next.next = head.nextÂ
    print(countNodesInLoop(head))     # This code is contributed by akshitaguprzj3 |
C#
using System;using System.Collections.Generic;Â
namespace Geek{    // Linked list node    class Node    {        public int data;        public Node next;    }    class GFG    {        // Function to detect and         // count loop nodes in the list        static int CountNodesInLoop(Node list)        {            HashSet<Node> visited = new HashSet<Node>();            Node current = list;            int count = 0;            while (current != null)            {                // If the node is already visited                 // it means there is a loop                if (visited.Contains(current))                {                    Node startOfLoop = current;                    do                    {                        count++;                        current = current.next;                    } while (current != startOfLoop);                    return count;                }                // Mark the current node as visited                visited.Add(current);                // Move to the next node                current = current.next;            }            // Return 0 to indicate that there is no loop            return 0;        }        static Node NewNode(int key)        {            Node temp = new Node();            temp.data = key;            temp.next = null;            return temp;        }        static void Main(string[] args)        {            Node head = NewNode(1);            head.next = NewNode(2);            head.next.next = NewNode(3);            head.next.next.next = NewNode(4);            head.next.next.next.next = NewNode(5);            head.next.next.next.next.next = head.next;            Console.WriteLine(CountNodesInLoop(head));            // Ensure console doesn't close immediately            Console.ReadLine();        }    }} |
Javascript
// Define a class for the linked list nodeclass Node {Â Â Â Â constructor(data) {Â Â Â Â Â Â Â Â this.data = data;Â Â Â Â Â Â Â Â this.next = null;Â Â Â Â }}Â
// Function to count nodes in a loop (if present) in the linked listfunction countNodesInLoop(list) {Â Â Â Â const visited = new Set();Â Â Â Â let current = list;Â Â Â Â let count = 0;Â
    while (current !== null) {        // If the node is already visited, it means there is a loop        if (visited.has(current)) {            const startOfLoop = current;            do {                count++;                current = current.next;            } while (current !== startOfLoop);            return count;        }Â
        // Mark the current node as visited        visited.add(current);Â
        // Move to the next node        current = current.next;    }Â
    // Return 0 to indicate that there is no loop    return 0;}Â
// Function to create a new nodefunction newNode(key) {Â Â Â Â const temp = new Node(key);Â Â Â Â return temp;}Â
// Driver codefunction main() {Â Â Â Â const head = newNode(1);Â Â Â Â head.next = newNode(2);Â Â Â Â head.next.next = newNode(3);Â Â Â Â head.next.next.next = newNode(4);Â Â Â Â head.next.next.next.next = newNode(5);Â
    // Create a loop for testing    head.next.next.next.next.next = head.next;Â
    console.log(countNodesInLoop(head));}Â
// Call the main function to test the codemain(); |
Output:
4
Time complexity:Â O(N), where N is the number of nodes in the linked list.
Auxiliary Space:Â O(N).
Related Articles:Â Â
This article is contributed by Shubham Gupta. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

