Linked List February 22 ,2026

Length of Loop in Linked List

Problem

Given the head of a Singly Linked List, determine the length of the loop (cycle) if a loop exists.

If no loop exists, return 0.

Example

Looped List

1 → 2 → 3 → 4 → 5
          ↑     ↓
          ← ← ← ←

Loop Length

3

(Loop contains nodes 3 → 4 → 5)

Approach 1 — Floyd’s Cycle Detection + Counting

Idea

  1. First detect the loop using slow and fast pointers
  2. When they meet, a loop exists
  3. From meeting point, traverse the loop until coming back to same node
  4. Count the nodes visited

Steps

  1. Initialize slow and fast at head
  2. Move:
    • slow → one step
    • fast → two steps
  3. If they meet → loop found
  4. Start counting from meeting point
  5. Move until returning to same node
  6. Return count

Time Complexity

O(N)

Space Complexity

O(1)

C Implementation

// While running this code, replace all #include "..." with #include <...>

#include  "stdio.h"
#include  "stdlib.h"

struct Node {
    int data;
    struct Node* next;
};

int countLoop(struct Node* head) {
    struct Node *slow = head, *fast = head;

    while (fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;

        if (slow == fast) {
            int count = 1;
            struct Node* temp = slow->next;

            while (temp != slow) {
                count++;
                temp = temp->next;
            }
            return count;
        }
    }
    return 0;
}

int main() {
    struct Node *head, *n2, *n3, *n4, *n5;

    head = (struct Node*)malloc(sizeof(struct Node));
    n2 = (struct Node*)malloc(sizeof(struct Node));
    n3 = (struct Node*)malloc(sizeof(struct Node));
    n4 = (struct Node*)malloc(sizeof(struct Node));
    n5 = (struct Node*)malloc(sizeof(struct Node));

    head->data = 1;
    n2->data = 2;
    n3->data = 3;
    n4->data = 4;
    n5->data = 5;

    head->next = n2;
    n2->next = n3;
    n3->next = n4;
    n4->next = n5;
    n5->next = n3; // loop starts at 3

    printf("%d", countLoop(head));

    return 0;
}

Output

3

C++ Implementation

// While running this code, replace all #include "..." with #include <...>

#include "iostream"
using namespace std;

class Node {
public:
    int data;
    Node* next;

    Node(int x) {
        data = x;
        next = NULL;
    }
};

int countLoop(Node* head) {
    Node *slow = head, *fast = head;

    while (fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;

        if (slow == fast) {
            int count = 1;
            Node* temp = slow->next;

            while (temp != slow) {
                count++;
                temp = temp->next;
            }
            return count;
        }
    }
    return 0;
}

int main() {
    Node* head = new Node(1);
    Node* n2 = new Node(2);
    Node* n3 = new Node(3);
    Node* n4 = new Node(4);
    Node* n5 = new Node(5);

    head->next = n2;
    n2->next = n3;
    n3->next = n4;
    n4->next = n5;
    n5->next = n3;

    cout << countLoop(head);

    return 0;
}

Output

3

Java Implementation

class Node {
    int data;
    Node next;

    Node(int d) {
        data = d;
        next = null;
    }
}

public class Main {

    static int countLoop(Node head) {
        Node slow = head, fast = head;

        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;

            if (slow == fast) {
                int count = 1;
                Node temp = slow.next;
                while (temp != slow) {
                    count++;
                    temp = temp.next;
                }
                return count;
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        Node n2 = new Node(2);
        Node n3 = new Node(3);
        Node n4 = new Node(4);
        Node n5 = new Node(5);

        head.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        n5.next = n3;

        System.out.println(countLoop(head));
    }
}

Output

3

Python Implementation

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

def count_loop(head):
    slow = fast = head

    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next

        if slow == fast:
            count = 1
            temp = slow.next
            while temp != slow:
                count += 1
                temp = temp.next
            return count
    return 0

head = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
n5 = Node(5)

head.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
n5.next = n3

print(count_loop(head))

Output

3

JavaScript Implementation

class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

function countLoop(head) {
    let slow = head;
    let fast = head;

    while (fast && fast.next) {
        slow = slow.next;
        fast = fast.next.next;

        if (slow === fast) {
            let count = 1;
            let temp = slow.next;
            while (temp !== slow) {
                count++;
                temp = temp.next;
            }
            return count;
        }
    }
    return 0;
}

let head = new Node(1);
let n2 = new Node(2);
let n3 = new Node(3);
let n4 = new Node(4);
let n5 = new Node(5);

head.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = n3;

console.log(countLoop(head));

Output

3

Approach 2 — Using Hash Set (Visited Nodes)

Idea

In this approach, we detect the loop and compute its length using a Hash Set.

While traversing:

  • Store each visited node in the set
  • If a node repeats → loop detected
  • Start counting nodes from that repeated node until we reach it again

Steps

  1. Create an empty Hash Set
  2. Traverse the list
  3. If node already exists in set → loop start found
  4. From that node, traverse until reaching same node again
  5. Count nodes in the loop
  6. Return count
  7. If traversal reaches NULL → return 0

Time Complexity

O(N)

Space Complexity

O(N)

C Implementation

// While running this code, replace all #include "..." with #include <...>

#include "stdio.h"
#include "stdlib.h"

#define MAX 1000

struct Node {
    int data;
    struct Node* next;
};

int countLoop(struct Node* head) {
    struct Node* visited[MAX];
    int count = 0;

    struct Node* temp = head;

    while (temp != NULL) {
        for (int i = 0; i < count; i++) {
            if (visited[i] == temp) {
                int loopLen = 1;
                struct Node* start = temp->next;

                while (start != temp) {
                    loopLen++;
                    start = start->next;
                }
                return loopLen;
            }
        }
        visited[count++] = temp;
        temp = temp->next;
    }
    return 0;
}

int main() {
    struct Node *head, *n2, *n3, *n4, *n5;

    head = (struct Node*)malloc(sizeof(struct Node));
    n2 = (struct Node*)malloc(sizeof(struct Node));
    n3 = (struct Node*)malloc(sizeof(struct Node));
    n4 = (struct Node*)malloc(sizeof(struct Node));
    n5 = (struct Node*)malloc(sizeof(struct Node));

    head->data = 1;
    n2->data = 2;
    n3->data = 3;
    n4->data = 4;
    n5->data = 5;

    head->next = n2;
    n2->next = n3;
    n3->next = n4;
    n4->next = n5;
    n5->next = n3;

    printf("%d", countLoop(head));

    return 0;
}

Output

3

C++ Implementation


// While running this code, replace all #include "..." with #include <...>

#include "iostream"
#include "unordered_set"
using namespace std;

class Node {
public:
    int data;
    Node* next;

    Node(int x) {
        data = x;
        next = NULL;
    }
};

int countLoop(Node* head) {
    unordered_set visited;  // FIXED

    Node* temp = head;

    while (temp != NULL) {
        if (visited.count(temp)) {
            int count = 1;
            Node* start = temp->next;

            while (start != temp) {
                count++;
                start = start->next;
            }
            return count;
        }
        visited.insert(temp);
        temp = temp->next;
    }
    return 0;
}

int main() {
    Node* head = new Node(1);
    Node* n2 = new Node(2);
    Node* n3 = new Node(3);
    Node* n4 = new Node(4);
    Node* n5 = new Node(5);

    head->next = n2;
    n2->next = n3;
    n3->next = n4;
    n4->next = n5;
    n5->next = n3;  // loop starts at node 3

    cout << countLoop(head);

    return 0;
}

Output

3

Java Implementation

import java.util.HashSet;

class Node {
    int data;
    Node next;

    Node(int d) {
        data = d;
        next = null;
    }
}

public class Main {

    static int countLoop(Node head) {
        HashSet visited = new HashSet<>();
        Node temp = head;

        while (temp != null) {
            if (visited.contains(temp)) {
                int count = 1;
                Node start = temp.next;
                while (start != temp) {
                    count++;
                    start = start.next;
                }
                return count;
            }
            visited.add(temp);
            temp = temp.next;
        }
        return 0;
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        Node n2 = new Node(2);
        Node n3 = new Node(3);
        Node n4 = new Node(4);
        Node n5 = new Node(5);

        head.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        n5.next = n3;

        System.out.println(countLoop(head));
    }
}

Output

3

Python Implementation

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

def count_loop(head):
    visited = set()
    temp = head

    while temp:
        if temp in visited:
            count = 1
            start = temp.next
            while start != temp:
                count += 1
                start = start.next
            return count
        visited.add(temp)
        temp = temp.next

    return 0

head = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
n5 = Node(5)

head.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
n5.next = n3

print(count_loop(head))

Output

3

JavaScript Implementation

class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

function countLoop(head) {
    let visited = new Set();
    let temp = head;

    while (temp !== null) {
        if (visited.has(temp)) {
            let count = 1;
            let start = temp.next;
            while (start !== temp) {
                count++;
                start = start.next;
            }
            return count;
        }
        visited.add(temp);
        temp = temp.next;
    }
    return 0;
}

let head = new Node(1);
let n2 = new Node(2);
let n3 = new Node(3);
let n4 = new Node(4);
let n5 = new Node(5);

head.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = n3;

console.log(countLoop(head));

Output

3

Next Problem in the series-

Design Browser History

Sanjiv
0

You must logged in to post comments.

Related Blogs

Introducti...
Linked List January 01 ,2026

Introduction to Link...

Length of...
Linked List January 01 ,2026

Length of a Singly L...

Remove Eve...
Linked List January 01 ,2026

Remove Every K-th No...

Middle of...
Linked List January 01 ,2026

Middle of a Linked L...

Count Occu...
Linked List January 01 ,2026

Count Occurrences in...

Circular L...
Linked List January 01 ,2026

Circular Linked List...

Check if a...
Linked List January 01 ,2026

Check if a Linked Li...

Count Node...
Linked List January 01 ,2026

Count Nodes in a Cir...

Deletion f...
Linked List January 01 ,2026

Deletion from a Circ...

Singly to...
Linked List January 01 ,2026

Singly to Circular L...

Exchange F...
Linked List January 01 ,2026

Exchange First and L...

Deletion i...
Linked List January 01 ,2026

Deletion in a Doubly...

Print a Si...
Linked List February 02 ,2026

Print a Singly Linke...

Search in...
Linked List February 02 ,2026

Search in a Singly L...

Linked Lis...
Linked List February 02 ,2026

Linked List Insertio...

Deleting a...
Linked List February 02 ,2026

Deleting a Given Key...

Deleting a...
Linked List February 02 ,2026

Deleting a Node at a...

Delete Ent...
Linked List February 02 ,2026

Delete Entire Linked...

Nth Node f...
Linked List February 02 ,2026

Nth Node from Start

Nth Node f...
Linked List February 02 ,2026

Nth Node from End

Size of Do...
Linked List February 02 ,2026

Size of Doubly Linke...

Reverse a...
Linked List February 02 ,2026

Reverse a Singly Lin...

Reverse a...
Linked List February 02 ,2026

Reverse a Doubly Lin...

Insert at...
Linked List February 02 ,2026

Insert at Beginning...

Insert at...
Linked List February 02 ,2026

Insert at End of Dou...

Delete Fir...
Linked List February 02 ,2026

Delete First Node of...

Check if L...
Linked List February 02 ,2026

Check if Linked List...

Copy a Lin...
Linked List February 02 ,2026

Copy a Linked List

Swap Nodes...
Linked List February 02 ,2026

Swap Nodes in Pairs

Detect Loo...
Linked List February 02 ,2026

Detect Loop in a Lin...

Design Bro...
Linked List February 02 ,2026

Design Browser Histo...

Get In Touch

Kurki bazar Uttar Pradesh

+91-8808946970

techiefreak87@gmail.com