Challenge: Detect Cycle in a Directed Graph

Here's another coding challenge on directed 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 directed graph and come upon a vertex that has already been visited.

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

Input

A directed graph.

Output

True if a cycle exists. False if it doesn’t.

Sample input

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

Sample output

True

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