Challenge: Detect Cycle in Graph

Here's another coding challenge on graphs. You'll implement a cool function which detects loops!

Problem Statement

The concept of loops or cycles is very common in graph theory. A cycle exists when you traverse the graph and come upon a vertex that has already been visited.

Note: Your solution should work for both connected and unconnected graphs.

You have to implement the detectCycle function which tells you whether or not a graph contains a cycle.


A graph in the form of an adjacency list

Note: You can start the traversal from any vertex.


true if a cycle exists. false if it doesn’t.

Sample Input

graph = {
    0 -> 1 
    1 -> 2
    2 -> 0

Sample Output


Level up your interview prep. Join Educative to access 70+ hands-on prep courses.