Open In App

Javascript Program For Finding The Length Of Loop In Linked List

Last Updated : 11 Jan, 2022
Like Article

Write a function detectAndCountLoop() that checks whether a given Linked List contains loop and if loop is present then returns count of nodes in loop. For example, the loop is present in below-linked list and length of the loop is 4. If the loop is not present, then the function should return 0.

It is known that 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 say (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.

  1. Find the common point in the loop by using the Floyd’s Cycle detection algorithm
  2. Store the pointer in a temporary variable and keep a count = 0
  3. Traverse the linked list until the same node is reached again and increase the count while moving to next node.
  4. Print the count as length of loop


// Javascript program to count number of nodes 
// in loop in a linked list if loop is 
// present 
// Link list node
class Node
    { = data; = null;
// Returns count of nodes present in loop.
function countNodes(n) 
    var res = 1;
    temp = n;
    while ( != n) 
        temp =;
    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 && 
  != null
        slow_p =;
        fast_p =;
        /* 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 code
head = newNode(1); = newNode(2); = newNode(3); = newNode(4); = newNode(5);
// Create a loop for testing =;
// This code contributed by gauravrajput1



Complexity Analysis:

  • Time complexity:O(n). 
    Only one traversal of the linked list is needed.
  • Auxiliary Space:O(1). 
    As no extra space is required.

Please refer complete article on Find length of loop in linked list for more details!

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads