The Wayback Machine - https://web.archive.org/web/20240808212204/https://www.geeksforgeeks.org/detect-loop-in-a-linked-list/
Open In App

Detect loop or cycle in a linked list

Last Updated : 31 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Given a linked list, check if the linked list has a loop (cycle) or not. The below diagram shows a linked list with a loop. 

Detect-loop-or-cycle-in-a-linked-list

Detect loop in a linked list using Hashing:

The idea is to insert the nodes in the hashmap and whenever a node is encountered that is already present in the hashmap then return true.

Follow the steps below to solve the problem:

  • Traverse the list individually and keep putting the node addresses in a Hash Table. 
  • At any point, if NULL is reached then return false 
  • If the next of the current nodes points to any of the previously stored nodes in Hash then return true.

Below is the implementation of the above approach:

C++
// C++ program to detect loop in a linked list
// using hashset
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* next;
    Node(int new_data) {
        this->data = new_data;
        this->next = nullptr;
    }
};

// Function that returns true if there is a loop in linked
// list else returns false.
bool detectLoop(Node* head) {
    unordered_set<Node*> h_map;

    // loop that runs till the head is nullptr
    while (head != nullptr) {

        // If this node is already present
        // in hashmap it means there is a cycle
        // (Because you will be encountering the
        // node for the second time).
        if (h_map.find(head) != h_map.end())
            return true;

        // If we are seeing the node for
        // the first time, insert it in hash
        h_map.insert(head);

        head = head->next;
    }
    return false;
}

// Driver code
int main() {

    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40 -> 50 -> 60
    Node* head = new Node(10);
    head->next = new Node(20);
    head->next->next = new Node(30);
    head->next->next->next = new Node(40);
    head->next->next->next->next = new Node(50);
    head->next->next->next->next->next = new Node(60);

    // Creating a loop resulting in the linked list:
    // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
    head->next->next->next->next = head;

    if (detectLoop(head))
        cout << "Loop Found";
    else
        cout << "No Loop";

    return 0;
}
C
// C program to detect loop in a linked list
// using hashset
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct Node {
    int data;
    struct Node* next;
};
struct Node* createNode(int new_data) {
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = NULL;
    return new_node;
}

// Function that returns true if there is a loop in linked
// list else returns false.
bool detectLoop(struct Node* head) {
  
      // Using array as a hash set substitute
    struct Node* set[100];
    int i = 0;

    // loop that runs till the head is NULL
    while (head != NULL) {

        // If this node is already present
        // in hashmap it means there is a cycle
        // (Because you will be encountering the
        // node for the second time).
        for (int j = 0; j < i; j++) {
            if (set[j] == head)
                return true;
        }

        // If we are seeing the node for
        // the first time, insert it in hash
        set[i++] = head;

        head = head->next;
    }
    return false;
}

// Driver code
int main() {

    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40 -> 50 -> 60
    struct Node* head = createNode(10);
    head->next = createNode(20);
    head->next->next = createNode(30);
    head->next->next->next = createNode(40);
    head->next->next->next->next = createNode(50);
    head->next->next->next->next->next = createNode(60);

    // Creating a loop resulting in the linked list:
    // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
    head->next->next->next->next = head;

    if (detectLoop(head))
        printf("Loop Found\n");
    else
        printf("No Loop\n");

    return 0;
}
Java
// Java program to detect loop in a linked list
// using hashset
import java.util.HashSet;
import java.util.Set;

class Node {
    int data;
    Node next;

    Node(int new_data) {
        this.data = new_data;
        this.next = null;
    }
}

class GfG {

    // Function that returns true if there is a loop in
    // linked list else returns false.
    static boolean detectLoop(Node head) {
        Set<Node> set = new HashSet<>();

        // loop that runs till the head is null
        while (head != null) {

            // If this node is already present
            // in hashmap it means there is a cycle
            // (Because you will be encountering the
            // node for the second time).
            if (set.contains(head))
                return true;

            // If we are seeing the node for
            // the first time, insert it in hash
            set.add(head);

            head = head.next;
        }
        return false;
    }

    // Driver code
    public static void main(String[] args) {

        // Create a hard-coded linked list:
        // 10 -> 20 -> 30 -> 40 -> 50 -> 60
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
        head.next.next.next.next = new Node(50);
        head.next.next.next.next.next = new Node(60);

        // Creating a loop resulting in the linked list:
        // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
        head.next.next.next.next = head;

        if (detectLoop(head))
            System.out.println("Loop Found");
        else
            System.out.println("No Loop");
    }
}
Python
# Python3 program to detect loop
# in the linked list using hashset

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

# Function that returns true if there is a loop in linked
# list else returns false.
def detect_loop(head):
    node_set = set()

    # loop that runs till the head is None
    while head is not None:

        # If this node is already present
        # in hashmap it means there is a cycle
        # (Because you will be encountering the
        # node for the second time).
        if head in node_set:
            return True

        # If we are seeing the node for
        # the first time, insert it in hash
        node_set.add(head)

        head = head.next
    return False

# Driver code
# Create a hard-coded linked list:
# 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70
head = Node(10)
head.next = Node(20)
head.next.next = Node(30)
head.next.next.next = Node(40)
head.next.next.next.next = Node(50)
head.next.next.next.next.next = Node(60)

# Creating a loop resulting in the linked list:
# 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
head.next.next.next.next = head

if detect_loop(head):
    print("Loop Found")
else:
    print("No Loop")
C#
// C# program to detect loop in a linked list
// using hashset
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node next;

    // Constructor to initialize the data and the next
    public Node(int new_data) {
        this.data = new_data;
        this.next = null;
    }
}

class GfG {

    // Function that returns true if there is a loop in
    // linked list else returns false.
    public static bool detectLoop(Node head) {
        HashSet<Node> set = new HashSet<Node>();

        // loop that runs till the head is null
        while (head != null) {

            // If this node is already present
            // in hashmap it means there is a cycle
            // (Because you will be encountering the
            // node for the second time).
            if (set.Contains(head))
                return true;

            // If we are seeing the node for
            // the first time, insert it in hash
            set.Add(head);

            head = head.next;
        }
        return false;
    }

    // Driver code
    static void Main() {

        // Create a hard-coded linked list:
        // 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
        head.next.next.next.next = new Node(50);
        head.next.next.next.next.next = new Node(60);

        // Creating a loop resulting in the linked list:
        // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
        head.next.next.next.next = head;

        if (detectLoop(head))
            Console.WriteLine("Loop Found");
        else
            Console.WriteLine("No Loop");
    }
}
JavaScript
// JavaScript program to detect loop in a linked list
// using hashset
class Node {
    constructor(new_data) {
        this.data = new_data;
        this.next = null;
    }
}

class GfG {

    // Function that returns true if there is a loop in
    // linked list else returns false.
    static detectLoop(head) {
        let set = new Set();

        // loop that runs till the head is null
        while (head !== null) {

            // If this node is already present
            // in hashmap it means there is a cycle
            // (Because you will be encountering the
            // node for the second time).
            if (set.has(head))
                return true;

            // If we are seeing the node for
            // the first time, insert it in hash
            set.add(head);

            head = head.next;
        }
        return false;
    }
}

// Driver code

// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70
let head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head.next.next.next.next = new Node(50);
head.next.next.next.next.next = new Node(60);

// Creating a loop resulting in the linked list:
// 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
head.next.next.next.next = head;

if (GfG.detectLoop(head))
    console.log("Loop Found");
else
    console.log("No Loop");

Output
Loop Found

Time complexity: O(N), Only one traversal of the loop is needed.
Auxiliary Space: O(N), N is the space required to store the value in the hashmap.

Detect loop in a linked list by Modification In Node Structure:

The idea is to modify the node structure by adding flag in it and mark the flag whenever visit the node.

Follow the steps below to solve the problem:

  • Have a visited flag with each node.
  • Traverse the linked list and keep marking visited nodes.
  • If you see a visited node again then there is a loop.

Below is the implementation of the above approach.

C++
// C++ program to detect loop in a linked list
// by modification in node structure
#include <bits/stdc++.h>
using namespace std;

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

    // Flag to mark the node visited
    int flag;
    Node(int new_data) {
        this->data = new_data;
        this->next = nullptr;
        this->flag = 0;
    }
};

// Function that returns true if there is a loop in linked
// list else returns false.
bool detectLoop(Node* head) {
    while (head != NULL) {

        // If this node is already traverse
        // it means there is a cycle
        // (Because you we encountering the
        // node for the second time).
        if (head->flag == 1)
            return true;

        // If we are seeing the node for
        // the first time, mark its flag as 1
        head->flag = 1;

        head = head->next;
    }
    return false;
}

// Driver code
int main() {

    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40 -> 50 -> 60
    Node* head = new Node(10);
    head->next = new Node(20);
    head->next->next = new Node(30);
    head->next->next->next = new Node(40);
    head->next->next->next->next = new Node(50);
    head->next->next->next->next->next = new Node(60);

    // Creating a loop resulting in the linked list:
    // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
    head->next->next->next->next = head;
  
    if (detectLoop(head))
        cout << "Loop Found";
    else
        cout << "No Loop";

    return 0;
}
C
// C program to detect loop in a linked list
// by modification in node structure
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;

    // Flag to mark the node visited
    int flag;
};
struct Node* createNode(int new_data) {
    struct Node* new_node
        = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = NULL;
    new_node->flag = 0;
    return new_node;
}

// Function that returns true if there is a loop in linked
// list else returns false.
bool detectLoop(struct Node* head) {
    while (head != NULL) {

        // If this node is already traversed
        // it means there is a cycle
        // (Because you are encountering the
        // node for the second time).
        if (head->flag == 1)
            return true;

        // If we are seeing the node for
        // the first time, mark its flag as 1
        head->flag = 1;

        head = head->next;
    }
    return false;
}

// Driver code
int main() {

    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40 -> 50 -> 60
    struct Node* head = createNode(10);
    head->next = createNode(20);
    head->next->next = createNode(30);
    head->next->next->next = createNode(40);
    head->next->next->next->next = createNode(50);
    head->next->next->next->next->next = createNode(60);

    // Creating a loop resulting in the linked list:
    // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
    head->next->next->next->next = head;

    if (detectLoop(head))
        printf("Loop Found\n");
    else
        printf("No Loop\n");

    return 0;
}
Java
// Java program to detect loop in a linked list
// by modification in node structure
import java.util.*;

class Node {
    int data;
    Node next;

    // Flag to mark the node visited
    int flag;
    Node(int new_data) {
        this.data = new_data;
        this.next = null;
        this.flag = 0;
    }
}

class GfG {

    // Function that returns true if there is a loop in
    // linked list else returns false.
    static boolean detectLoop(Node head) {
        while (head != null) {

            // If this node is already traversed
            // it means there is a cycle
            // (Because you are encountering the
            // node for the second time).
            if (head.flag == 1)
                return true;

            // If we are seeing the node for
            // the first time, mark its flag as 1
            head.flag = 1;
            head = head.next;
        }
        return false;
    }

    // Driver code
    public static void main(String[] args) {

        // Create a hard-coded linked list:
        // 10 -> 20 -> 30 -> 40 -> 50 -> 60
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
        head.next.next.next.next = new Node(50);
        head.next.next.next.next.next = new Node(60);

        // Creating a loop resulting in the linked list:
        // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
        head.next.next.next.next = head;

        if (detectLoop(head))
            System.out.println("Loop Found");
        else
            System.out.println("No Loop");
    }
}
Python
# Python program to detect loop in a linked list
# by modification in node structure
class Node:
  
      # Constructor to initialize the data and the next
    def __init__(self, new_data):
        self.data = new_data
        self.next = None
        
        # Flag to mark the node visited
        self.flag = 0

# Function that returns true if there is a loop in linked
# list else returns false.
def detect_loop(head):
    while head is not None:
      
        # If this node is already traversed
        # it means there is a cycle
        # (Because you are encountering the
        # node for the second time).
        if head.flag == 1:
            return True

        # If we are seeing the node for
        # the first time, mark its flag as 1
        head.flag = 1

        head = head.next
    return False

# Driver code

# Create a hard-coded linked list:
# 10 -> 20 -> 30 -> 40 -> 50 -> 60
head = Node(10)
head.next = Node(20)
head.next.next = Node(30)
head.next.next.next = Node(40)
head.next.next.next.next = Node(50)
head.next.next.next.next.next = Node(60)

# Creating a loop resulting in the linked list:
# 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
head.next.next.next.next = head

if detect_loop(head):
    print("Loop Found")
else:
    print("No Loop")
C#
// C# program to detect loop in a linked list
// by modification in node structure
using System;

class Node {
    public int data;
    public Node next;
  
      // Flag to mark the node visited
    public int flag;
    public Node(int new_data) {
        this.data = new_data;
        this.next = null;
        this.flag = 0;
    }
}

class GfG {

    // Function that returns true if there is a loop in
    // linked list else returns false.
    public static bool detectLoop(Node head) {
        while (head != null) {

            // If this node is already traversed
            // it means there is a cycle
            // (Because you are encountering the
            // node for the second time).
            if (head.flag == 1)
                return true;

            // If we are seeing the node for
            // the first time, mark its flag as 1
            head.flag = 1;

            head = head.next;
        }
        return false;
    }

    // Driver code
    static void Main() {

        // Create a hard-coded linked list:
        // 10 -> 20 -> 30 -> 40 -> 50 -> 60
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
        head.next.next.next.next = new Node(50);
        head.next.next.next.next.next = new Node(60);

        // Creating a loop resulting in the linked list:
        // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
        head.next.next.next.next = head;

        if (detectLoop(head))
            Console.WriteLine("Loop Found");
        else
            Console.WriteLine("No Loop");
    }
}
JavaScript
// JavaScript program to detect loop in a linked list
// by modification in node structure

class Node {
    constructor(new_data) {
        this.data = new_data;
        this.next = null;
        
         // Flag to mark the node visited
        this.flag = 0;
    }
}

class GfG {

    // Returns true if there is a loop in linked list
    // else returns false.
    static detectLoop(head) {
        while (head !== null) {

            // If this node is already traversed
            // it means there is a cycle
            // (Because you are encountering the
            // node for the second time).
            if (head.flag === 1)
                return true;

            // If we are seeing the node for
            // the first time, mark its flag as 1
            head.flag = 1;

            head = head.next;
        }
        return false;
    }
}

// Driver code

// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40 -> 50 -> 60
let head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head.next.next.next.next = new Node(50);
head.next.next.next.next.next = new Node(60);

// Creating a loop resulting in the linked list:
// 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
head.next.next.next.next = head;

if (GfG.detectLoop(head))
    console.log("Loop Found");
else
    console.log("No Loop");

Output
Loop Found

Time complexity: O(N), Only one traversal of the loop is needed.
Auxiliary Space: O(1)

Detect loop in a linked list using Floyd’s Cycle-Finding Algorithm:

This algorithm is used to find a loop in a linked list. It uses two pointers one moving twice as fast as the other one. The faster one is called the faster pointer and the other one is called the slow pointer.

Follow the steps below to solve the problem:

  • Traverse linked list using two pointers.
  • Move one pointer(slow_p) by one and another pointer(fast_p) by two.
  • If these pointers meet at the same node then there is a loop. If pointers do not meet then the linked list doesn’t have a loop.

Illustration:


Implementation of Floyd’s Cycle-Finding Algorithm:  

C++
// C++ program to detect loop in a linked list
// using Floyd's Cycle-Finding Algorithm
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* next;
    Node(int new_data) {
        this->data = new_data;
        this->next = nullptr;
    }
};

// Function that returns true if there is a loop in linked
// list else returns false.
int detectLoop(Node* head) 
{
    // Fast and slow pointers initially points to the head
    Node *slow_p = head, *fast_p = head;

    // Loop that runs while fast and slow pointer are not
    // nullptr and not equal
    while (slow_p && fast_p && fast_p->next) {
        slow_p = slow_p->next;
        fast_p = fast_p->next->next;

        // If fast and slow pointer points to the same node,
        // then the cycle is detected
        if (slow_p == fast_p) {
            return 1;
        }
    }
    return 0;
}

// Driver code
int main() {

    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40 -> 50 -> 60
    Node* head = new Node(10);
    head->next = new Node(20);
    head->next->next = new Node(30);
    head->next->next->next = new Node(40);
    head->next->next->next->next = new Node(50);
    head->next->next->next->next->next = new Node(60);

    // Creating a loop resulting in the linked list:
    // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
    head->next->next->next->next = head;

    if (detectLoop(head))
        cout << "Loop Found";
    else
        cout << "No Loop";

    return 0;
}
C
// C program to detect loop in a linked list
// using Floyd's Cycle-Finding Algorithm
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

// A linked list node
struct Node {
    int data;
    struct Node* next;
};
struct Node* createNode(int new_data) {
    struct Node* new_node
        = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = NULL;
    return new_node;
}

// Function that returns true if there is a loop in linked
// list else returns false.
int detectLoop(struct Node* head) {
  
    // Fast and slow pointers initially points to the head
    struct Node *slow_p = head, *fast_p = head;

    // Loop that runs while fast and slow pointer are not
    // nullptr and not equal
    while (slow_p && fast_p && fast_p->next) {
        slow_p = slow_p->next;
        fast_p = fast_p->next->next;

        // If fast and slow pointer points to the same node,
        // then the cycle is detected
        if (slow_p == fast_p) {
            return 1;
        }
    }
    return 0;
}

// Driver code
int main()
{

    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40 -> 50 -> 60
    struct Node* head = createNode(10);
    head->next = createNode(20);
    head->next->next = createNode(30);
    head->next->next->next = createNode(40);
    head->next->next->next->next = createNode(50);
    head->next->next->next->next->next = createNode(60);

    // Creating a loop resulting in the linked list:
    // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
    head->next->next->next->next = head;

    if (detectLoop(head))
        printf("Loop Found\n");
    else
        printf("No Loop\n");

    return 0;
}
Java
// Java program to detect loop in a linked list
// using Floyd's Cycle-Finding Algorithm
import java.util.*;

class Node {
    int data;
    Node next;

    Node(int new_data) {
        this.data = new_data;
        this.next = null;
    }
}

class GfG {

    // Function that returns true if there is a loop in
    // linked list else returns false.
    static boolean detectLoop(Node head)
    {
        // Fast and slow pointers initially points to the
        // head
        Node slow_p = head, fast_p = head;

        // Loop that runs while fast and slow pointer are
        // not null and not equal
        while (slow_p != null && fast_p != null
               && fast_p.next != null) {
            slow_p = slow_p.next;
            fast_p = fast_p.next.next;

            // If fast and slow pointer points to the same
            // node, then the cycle is detected
            if (slow_p == fast_p) {
                return true;
            }
        }
        return false;
    }

    // Driver code
    public static void main(String[] args)
    {

        // Create a hard-coded linked list:
        // 10 -> 20 -> 30 -> 40 -> 50 -> 60
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
        head.next.next.next.next = new Node(50);
        head.next.next.next.next.next = new Node(60);

        // Creating a loop resulting in the linked list:
        // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
        head.next.next.next.next = head;


        if (detectLoop(head))
            System.out.println("Loop Found");
        else
            System.out.println("No Loop");
    }
}
Python
# C++ program to detect loop in a linked list
# using Floyd's Cycle-Finding Algorithm
class Node:
    def __init__(self, new_data):
        self.data = new_data
        self.next = None

# Function that returns true if there is a loop in linked
# list else returns false.
def detect_loop(head):

    # Fast and slow pointers initially points to the head
    slow_p = head
    fast_p = head

    # Loop that runs while fast and slow pointer are not
    # None and not equal
    while slow_p and fast_p and fast_p.next:
        slow_p = slow_p.next
        fast_p = fast_p.next.next

        # If fast and slow pointer points to the same node,
        # then the cycle is detected
        if slow_p == fast_p:
            return True
    return False

# Driver code


# Create a hard-coded linked list:
# 10 -> 20 -> 30 -> 40 -> 50 -> 60
head = Node(10)
head.next = Node(20)
head.next.next = Node(30)
head.next.next.next = Node(40)
head.next.next.next.next = Node(50)
head.next.next.next.next.next = Node(60)

# Creating a loop resulting in the linked list:
# 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
head.next.next.next.next = head

if detect_loop(head):
    print("Loop Found")
else:
    print("No Loop")
C#
// C# program to detect loop in a linked list
// using Floyd's Cycle-Finding Algorithm
using System;

class Node {
    public int data;
    public Node next;
    public Node(int new_data) {
        this.data = new_data;
        this.next = null;
    }
}

class GfG {

    // Function that returns true if there is a loop in linked
    // list else returns false.
    public static bool detectLoop(Node head) {
        // Fast and slow pointers initially points to the head
        Node slow_p = head, fast_p = head;

        // Loop that runs while fast and slow pointer are not
        // null and not equal
        while (slow_p != null && fast_p != null && fast_p.next != null) {
            slow_p = slow_p.next;
            fast_p = fast_p.next.next;

            // If fast and slow pointer points to the same node,
            // then the cycle is detected
            if (slow_p == fast_p) {
                return true;
            }
        }
        return false;
    }

    // Driver code
    static void Main() {

        // Create a hard-coded linked list:
        // 10 -> 20 -> 30 -> 40 -> 50 -> 60
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
        head.next.next.next.next = new Node(50);
        head.next.next.next.next.next = new Node(60);

        // Creating a loop resulting in the linked list:
        // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
        head.next.next.next.next = head;

        if (detectLoop(head))
            Console.WriteLine("Loop Found");
        else
            Console.WriteLine("No Loop");
    }
}
JavaScript
// Javascript program to detect loop in a linked list
// using Floyd's Cycle-Finding Algorithm
class Node {
    constructor(new_data) {
        this.data = new_data;
        this.next = null;
    }
}

class GfG {

    // Function that returns true if there is a loop in
    // linked list else returns false.
    static detectLoop(head) {
        // Fast and slow pointers initially points to the
        // head
        let slow_p = head, fast_p = head;

        // Loop that runs while fast and slow pointer are
        // not null and not equal
        while (slow_p !== null && fast_p !== null
               && fast_p.next !== null) {
            slow_p = slow_p.next;
            fast_p = fast_p.next.next;

            // If fast and slow pointer points to the same
            // node, then the cycle is detected
            if (slow_p === fast_p) {
                return true;
            }
        }
        return false;
    }
}

// Driver code

// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40 -> 50 -> 60
let head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head.next.next.next.next = new Node(50);
head.next.next.next.next.next = new Node(60);

// Creating a loop resulting in the linked list:
// 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
head.next.next.next.next = head;

if (GfG.detectLoop(head))
    console.log("Loop Found");
else
    console.log("No Loop");

Output
Loop Found

Time complexity: O(N), Only one traversal of the loop is needed.
Auxiliary Space: O(1). 

Detect loop in a linked list by Marking visited nodes without modifying Node structure:

The idea is to point the current node of the linked list to a node which is created. Whenever a node’s next is pointing to that node it means loop is there.

Follow the steps below to solve the problem:

  • A temporary node is created. 
  • The next pointer of each node that is traversed is made to point to this temporary node. 
  • This way we are using the next pointer of a node as a flag to indicate whether the node has been traversed or not. 
  • Every node is checked to see if the next is pointing to a temporary node or not.
  • In the case of the first node of the loop, the second time we traverse it this condition will be true, hence we find that loop exists. 
  • If we come across a node that points to null then the loop doesn’t exist.

Below is the implementation of the above approach:

C++
// C++ program to find the loop in the linked list by
// marking visited nodes without modifying Node structure
#include <bits/stdc++.h>
using namespace std;

class Node {
  public:
    int data;
    Node* next;
    Node(int new_data) {
        this->data = new_data;
        this->next = NULL;
    }
};

// Function to detect first node of loop
// in a linked list that may contain loop
bool detectLoop(Node* head) {
  
    // Create a temporary node
    Node* temp = new Node(0);
  
    while (head != NULL) {
      
        // This condition is for the case when there is no
        // loop
        if (head->next == NULL)
            return false;
      
        // Check if next is already pointing to temp
        if (head->next == temp)
            return true;
      
        // Store the pointer to the next node
        // in order to get to it in the next step
        Node* next = head->next;
      
        // Make next point to temp
        head->next = temp;
      
        // Get to the next node in the list
        head = next;
    }
    return false;
}

// Driver code
int main() {

    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40 -> 50 -> 60
    Node* head = new Node(10);
    head->next = new Node(20);
    head->next->next = new Node(30);
    head->next->next->next = new Node(40);
    head->next->next->next->next = new Node(50);
    head->next->next->next->next->next = new Node(60);

    // Creating a loop resulting in the linked list:
    // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
    head->next->next->next->next = head;

    if (detectLoop(head))
        cout << "Loop Found";
    else
        cout << "No Loop";

    return 0;
}
C
// C program to find the loop in the linked list by
// marking visited nodes without modifying Node structure
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};
struct Node* createNode(int new_data) {
    struct Node* new_node
        = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = NULL;
    return new_node;
}

// Function to detect the loop in a linked list
bool detectLoop(struct Node* head) {
    // Create a temporary node
    struct Node* temp = createNode(0);

    while (head != NULL) {

        // This condition is for the case when there is no
        // loop
        if (head->next == NULL)
            return false;

        // Check if next is already pointing to temp
        if (head->next == temp)
            return true;

        // Store the pointer to the next node
        // in order to get to it in the next step
        struct Node* next = head->next;

        // Make next point to temp
        head->next = temp;

        // Get to the next node in the list
        head = next;
    }
    return false;
}

// Driver code
int main() {

    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40 -> 50 -> 60
    struct Node* head = createNode(10);
    head->next = createNode(20);
    head->next->next = createNode(30);
    head->next->next->next = createNode(40);
    head->next->next->next->next = createNode(50);
    head->next->next->next->next->next = createNode(60);

    // Creating a loop resulting in the linked list:
    // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
    head->next->next->next->next = head;

    if (detectLoop(head))
        printf("Loop Found\n");
    else
        printf("No Loop\n");

    return 0;
}
Java
// Java program to find the loop in the linked list by
// marking visited nodes without modifying Node structure
class Node {
    int data;
    Node next;
    Node(int new_data) {
        this.data = new_data;
        this.next = null;
    }
}

class GfG {

    // Function to detect the loop in a linked list
    static boolean detectLoop(Node head) {

        // Create a temporary node
        Node temp = new Node(0);

        while (head != null) {

            // This condition is for the case when there is
            // no loop
            if (head.next == null)
                return false;

            // Check if next is already pointing to temp
            if (head.next == temp)
                return true;

            // Store the pointer to the next node
            // in order to get to it in the next step
            Node next = head.next;

            // Make next point to temp
            head.next = temp;

            // Get to the next node in the list
            head = next;
        }
        return false;
    }

    // Driver code
    public static void main(String[] args) {

        // Create a hard-coded linked list:
        // 10 -> 20 -> 30 -> 40 -> 50 -> 60
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
        head.next.next.next.next = new Node(50);
        head.next.next.next.next.next = new Node(60);

        // Creating a loop resulting in the linked list:
        // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
        head.next.next.next.next = head;

        if (detectLoop(head))
            System.out.println("Loop Found");
        else
            System.out.println("No Loop");
    }
}
Python
# Python program to find the loop in the linked list by
# marking visited nodes without modifying Node structure
class Node:
    def __init__(self, new_data):
        self.data = new_data
        self.next = None


def detect_loop(head):

    # Create a temporary node
    temp = Node(0)

    while head is not None:

        # This condition is for the case when there is no loop
        if head.next is None:
            return False

        # Check if next is already pointing to temp
        if head.next == temp:
            return True

        # Store the pointer to the next node
        # in order to get to it in the next step
        next_node = head.next

        # Make next point to temp
        head.next = temp

        # Get to the next node in the list
        head = next_node
    return False

# Driver code

# Create a hard-coded linked list:
# 10 -> 20 -> 30 -> 40 -> 50 -> 60
head = Node(10)
head.next = Node(20)
head.next.next = Node(30)
head.next.next.next = Node(40)
head.next.next.next.next = Node(50)
head.next.next.next.next.next = Node(60)

# Creating a loop resulting in the linked list:
# 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
head.next.next.next.next = head

if detect_loop(head):
    print("Loop Found")
else:
    print("No Loop")
C#
// C# program to find the loop in the linked list by
// marking visited nodes without modifying Node structure
using System;

class Node {
    public int data;
    public Node next;
    public Node(int new_data) {
        this.data = new_data;
        this.next = null;
    }
}

class GfG {

    // Function to detect the loop in a linked list
    public static bool detectLoop(Node head)
    {
        // Create a temporary node
        Node temp = new Node(0);

        while (head != null) {

            // This condition is for the case when there is
            // no loop
            if (head.next == null)
                return false;

            // Check if next is already pointing to temp
            if (head.next == temp)
                return true;

            // Store the pointer to the next node
            // in order to get to it in the next step
            Node next = head.next;

            // Make next point to temp
            head.next = temp;

            // Get to the next node in the list
            head = next;
        }
        return false;
    }

    // Driver code
    static void Main()
    {

        // Create a hard-coded linked list:
        // 10 -> 20 -> 30 -> 40 -> 50 -> 60
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
        head.next.next.next.next = new Node(50);
        head.next.next.next.next.next = new Node(60);

        // Creating a loop resulting in the linked list:
        // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
        head.next.next.next.next = head;

        if (detectLoop(head))
            Console.WriteLine("Loop Found");
        else
            Console.WriteLine("No Loop");
    }
}
JavaScript
// Javascript program to find the loop in the linked list by
// marking visited nodes without modifying Node structure
class Node {
    constructor(new_data) {
        this.data = new_data;
        this.next = null;
    }
}

class GfG {

    // Function to detect the loop in a linked list
    static detectLoop(head) 
    {
        // Create a temporary node
        let temp = new Node(0);

        while (head !== null) {

            // This condition is for the case when there is
            // no loop
            if (head.next === null)
                return false;

            // Check if next is already pointing to temp
            if (head.next === temp)
                return true;

            // Store the pointer to the next node
            // in order to get to it in the next step
            let next = head.next;

            // Make next point to temp
            head.next = temp;

            // Get to the next node in the list
            head = next;
        }
        return false;
    }
}

// Driver code

// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40 -> 50 -> 60
let head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head.next.next.next.next = new Node(50);
head.next.next.next.next.next = new Node(60);

// Creating a loop resulting in the linked list:
// 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
head.next.next.next.next = head;

if (GfG.detectLoop(head))
    console.log("Loop Found");
else
    console.log("No Loop");

Output
Loop Found

Time complexity: O(N). Only one traversal of the loop is needed.
Auxiliary Space: O(1) 

Detect loop in a linked list by Storing length:

The idea is to store the length of the list from first node and last node, increment last node till reaches NULL or number of nodes in last is greater the current between first and last nodes.

Follow the steps below to solve the problem:

  • In this method, two pointers are created, first (always points to head) and last. 
  • Each time the last pointer moves calculate no of nodes between the first and last. 
  • check whether the current no of nodes > previous no of nodes 
    • If yes we proceed by moving the last pointer 
    • Else it means we’ve reached the end of the loop, so return output accordingly.

Below is the implementation of the above approach:

C++
// C++ Program to find the cycle in the linked list by
// storing the length
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* next;
    Node(int new_data) {
        this->data = new_data;
        this->next = NULL;
    }
};

// Helper function that returns distance between first and
// last node every time last node moves forwards
int distance(Node* first, Node* last) {

    // Counts number of nodes between first and last
    int count = 0;

    Node* curr;
    curr = first;
    while (curr != last) {
        count += 1;
        curr = curr->next;
    }
    return count + 1;
}

// Function to detect first node of loop
// in a linked list that may contain loop
bool detectLoop(Node* head) {

    Node *first, *last;

    // first always points to head
    first = head;

    // last pointer initially points to head
    last = head;

    // current_length stores no of nodes between current
    // position of first and last
    int current_length = 0;

    // prev_length stores no of nodes between previous
    // position of first and last
    int prev_length = -1;

    while (current_length > prev_length && last != NULL) {

        // set prev_length to current length then update the
        // current length
        prev_length = current_length;

        // distance is calculated
        current_length = distance(first, last);

        // last node points the next node
        last = last->next;
    }

    if (last == NULL) {
        return false;
    }
    else {
        return true;
    }
}

// Driver code
int main() {

    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40 -> 50 -> 60
    Node* head = new Node(10);
    head->next = new Node(20);
    head->next->next = new Node(30);
    head->next->next->next = new Node(40);
    head->next->next->next->next = new Node(50);
    head->next->next->next->next->next = new Node(60);

    // Creating a loop resulting in the linked list:
    // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
    head->next->next->next->next = head;

    if (detectLoop(head))
        cout << "Loop Found";
    else
        cout << "No Loop";

    return 0;
}
C
// C Program to find the cycle in the linked list by
// storing the length
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};
struct Node* createNode(int new_data) {
    struct Node* new_node
        = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = NULL;
    return new_node;
}

// Helper function that returns distance between first and
// last node every time last node moves forwards
int distance(struct Node* first, struct Node* last) {

    // Counts number of nodes between first and last
    int count = 0;
    struct Node* curr = first;
    while (curr != last) {
        count += 1;
        curr = curr->next;
    }
    return count + 1;
}

// Function to detect first node of loop
// in a linked list that may contain loop
bool detectLoop(struct Node* head) {
    struct Node* first = head;
    struct Node* last = head;

    int current_length = 0;
    int prev_length = -1;

    while (current_length > prev_length && last != NULL) {

        // set prev_length to current length then update the
        // current length
        prev_length = current_length;

        // distance is calculated
        current_length = distance(first, last);

        // last node points to the next node
        last = last->next;
    }

    if (last == NULL) {
        return false;
    }
    else {
        return true;
    }
}

// Driver code
int main() {

    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40 -> 50 -> 60
    struct Node* head = createNode(10);
    head->next = createNode(20);
    head->next->next = createNode(30);
    head->next->next->next = createNode(40);
    head->next->next->next->next = createNode(50);
    head->next->next->next->next->next = createNode(60);

    // Creating a loop resulting in the linked list:
    // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
    head->next->next->next->next = head;

    if (detectLoop(head))
        printf("Loop Found\n");
    else
        printf("No Loop\n");

    return 0;
}
Java
// Java Program to find the cycle in the linked list by
// storing the length
class Node {
    int data;
    Node next;
    Node(int new_data) {
        this.data = new_data;
        this.next = null;
    }
}

class GfG {

    // Helper function that returns distance between first
    // and last node every time last node moves forwards
    static int distance(Node first, Node last) {
      
        // Counts number of nodes between first and last
        int count = 0;
        Node curr = first;
        while (curr != last) {
            count += 1;
            curr = curr.next;
        }
        return count + 1;
    }

    // Function to detect first node of loop
    // in a linked list that may contain loop
    static boolean detectLoop(Node head) {
        Node first = head;
        Node last = head;

        int current_length = 0;
        int prev_length = -1;

        while (current_length > prev_length
               && last != null) {
          
            // set prev_length to current length then update
            // the current length
            prev_length = current_length;

            // distance is calculated
            current_length = distance(first, last);

            // last node points to the next node
            last = last.next;
        }

        return last != null;
    }

    // Driver code
    public static void main(String[] args) {

        // Create a hard-coded linked list:
        // 10 -> 20 -> 30 -> 40 -> 50 -> 60
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
        head.next.next.next.next = new Node(50);
        head.next.next.next.next.next = new Node(60);

        // Creating a loop resulting in the linked list:
        // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
        head.next.next.next.next = head;

        if (detectLoop(head))
            System.out.println("Loop Found");
        else
            System.out.println("No Loop");
    }
}
Python
# Python Program to find the cycle in the linked
# list by storing the length
class Node:
    def __init__(self, new_data):
        self.data = new_data
        self.next = None

# Helper function that returns distance between first
# and last node every time last node moves forwards
def distance(first, last):
    # Counts number of nodes between first and last
    count = 0
    curr = first
    while curr != last:
        count += 1
        curr = curr.next
    return count + 1

# Function to detect first node of loop
# in a linked list that may contain loop
def detect_loop(head):
    first = head
    last = head

    current_length = 0
    prev_length = -1

    while current_length > prev_length and last is not None:
      
        # set prev_length to current length then
        # update the current length
        prev_length = current_length

        # distance is calculated
        current_length = distance(first, last)

        # last node points to the next node
        last = last.next

    return last is not None

# Driver code

# Create a hard-coded linked list:
# 10 -> 20 -> 30 -> 40 -> 50 -> 60
head = Node(10)
head.next = Node(20)
head.next.next = Node(30)
head.next.next.next = Node(40)
head.next.next.next.next = Node(50)
head.next.next.next.next.next = Node(60)

# Creating a loop resulting in the linked list:
# 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
head.next.next.next.next = head

# Example of checking whether the linked list
# contains loop
if detect_loop(head):
    print("Loop Found")
else:
    print("No Loop")
C#
// C# Program to find the cycle in the linked list by
// storing the length
using System;

class Node {
    public int data;
    public Node next;
    public Node(int new_data) {
        this.data = new_data;
        this.next = null;
    }
}

class GfG {

    // Helper function that returns distance between first
    // and last node every time last node moves forwards
    public static int distance(Node first, Node last) {

        // Counts number of nodes between first and last
        int count = 0;
        Node curr = first;
        while (curr != last) {
            count += 1;
            curr = curr.next;
        }
        return count + 1;
    }

    // Function to detect first node of loop
    // in a linked list that may contain loop
    public static bool detectLoop(Node head) {
        Node first = head;
        Node last = head;

        int current_length = 0;
        int prev_length = -1;

        while (current_length > prev_length
               && last != null) {
            // set prev_length to current length then update
            // the current length
            prev_length = current_length;

            // distance is calculated
            current_length = distance(first, last);

            // last node points to the next node
            last = last.next;
        }

        return last != null;
    }

    // Driver code
    static void Main() {

        // Create a hard-coded linked list:
        // 10 -> 20 -> 30 -> 40 -> 50 -> 60
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
        head.next.next.next.next = new Node(50);
        head.next.next.next.next.next = new Node(60);

        // Creating a loop resulting in the linked list:
        // 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
        head.next.next.next.next = head;

        if (detectLoop(head))
            Console.WriteLine("Loop Found");
        else
            Console.WriteLine("No Loop");
    }
}
JavaScript
// Javascript program to find the cycle in the linked list
// by storing the length
class Node {
    constructor(new_data) {
        this.data = new_data;
        this.next = null;
    }
}

class GfG {

    // Helper function that returns distance between first
    // and last node every time last node moves forwards
    static distance(first, last) {
        // Counts number of nodes between first and last
        let count = 0;
        let curr = first;
        while (curr !== last) {
            count += 1;
            curr = curr.next;
        }
        return count + 1;
    }

    // Function to detect first node of loop
    // in a linked list that may contain loop
    static detectLoop(head) {
        let first = head;
        let last = head;

        let current_length = 0;
        let prev_length = -1;

        while (current_length > prev_length
               && last !== null) {
            // set prev_length to current length then update
            // the current length
            prev_length = current_length;

            // distance is calculated
            current_length = GfG.distance(first, last);

            // last node points to the next node
            last = last.next;
        }

        return last !== null;
    }
}

// Driver code

// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40 -> 50 -> 60
let head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head.next.next.next.next = new Node(50);
head.next.next.next.next.next = new Node(60);

// Creating a loop resulting in the linked list:
// 10 -> 20 -> 30 -> 40 -> 10 -> 20 -> 30 ...
head.next.next.next.next = head;

if (GfG.detectLoop(head))
    console.log("Loop Found");
else
    console.log("No Loop");

Output
Loop Found

Time complexity: O(N2), For every node calculate the length of that node from the head by traversing.
Auxiliary Space: O(1)




Similar Reads

Detect Cycle in a Linked List using Map
Given a Linked List, check if the linked list has a loop or not.There are various methods shown here: Detect Cycle in Linked List Example Input: 20-&gt;4-&gt;54-&gt;6-&gt;NULL Output: No loop is detected. Explanation: While traversing the linked list, we reach the end of the linked list. Therefore, no loop is present in the linked list. Input: 20-
7 min read
Detect and Remove Loop in Linked List
Given a linked list, the task is to check if there is a loop present in it and remove it. Example: Consider the below linked list where the node 5 links to node 3 forming a loop in the linked list. The task is to remove the loop in the linked list by updating the next pointer of node 5 point to NULL. Table of Content Approach 1- Using Hashing - O(N
15+ min read
Find length of loop/cycle in given Linked List
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: 4Explanation: The loop is present in the below-linked list and the length of the loop is 4. Input: linked list = 4 -&gt; 3 -&gt; 7 -&gt; 9 -&gt; 2
15 min read
Detect a negative cycle in a Graph | (Bellman Ford)
Given a directed weighted graph, the task is to find whether the given graph contains any negative-weight cycle or not. Note: A negative-weight cycle is a cycle in a graph whose edges sum to a negative value. Example: Input: Output: No Input: Output: Yes Algorithm to Find Negative Cycle in a Directed Weighted Graph Using Bellman-Ford:Initialize dis
15+ min read
Detect cycle in the graph using degrees of nodes of graph
Given a graph, the task is to detect a cycle in the graph using degrees of the nodes in the graph and print all the nodes that are involved in any of the cycles. If there is no cycle in the graph then print -1. Examples: Input: Output: 0 1 2 Approach: Recursively remove all vertices of degree 1. This can be done efficiently by storing a map of vert
11 min read
Detect cycle in Directed Graph using Topological Sort
Given a Directed Graph consisting of N vertices and M edges and a set of Edges[][], the task is to check whether the graph contains a cycle or not using Topological sort. Topological sort of directed graph is a linear ordering of its vertices such that, for every directed edge U -&gt; V from vertex U to vertex V, U comes before V in the ordering. E
9 min read
Detect Cycle in a 2D grid
Given a 2D grid arr[][] with different characters, the task is to detect whether it contains a cycle or not. A sequence of characters or integers c1, c2, .... cM is called a cycle if and only if it meets the following condition: M should at least be 4.All characters belong to the same character or integer. For all 0 &lt;= i &lt;= M -1 : ci and ci +
15 min read
Detect a negative cycle in a Graph using Shortest Path Faster Algorithm
Given a graph G consisting of nodes valued [0, N - 1], a source S, and an array Edges[][3] of type {u, v, w} that denotes that there is a directed edge between node u and v with weight w, the task is to check if there exists a negative cycle from the given source. If found to be true, then print "Yes". Otherwise, print "No". A negative cycle is a c
11 min read
Detect Cycle in a Directed Graph using BFS
Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains two cycles 0-&gt;1-&gt;2-&gt;3-&gt;0 and 2-&gt;4-&gt;2, so your function must return true. Recommended: Please solve it on "PRACTICE" f
11 min read
Detect Cycle in Graph using DSU
Given an undirected graph, the task is to check if the graph contains a cycle or not, using DSU. Examples: Input: The following is the graph Output: YesExplanation: There is a cycle of vertices {0, 1, 2}. Recommended PracticeDetect Cycle using DSUTry It!We already have discussed an algorithm to detect cycle in directed graph. Here Union-Find Algori
13 min read
three90RightbarBannerImg