Detect a Cycle in a Directed Graph

medium

Given a directed graph with V vertices (0 .. V-1) and directed edges edges (each [u, v] is an edge u → v), return true if it contains a cycle and false otherwise.

Hints

The undirected parent trick fails — a directed graph can re-reach a node without a cycle.
DFS while tracking which vertices are on the current recursion path.
An edge to a vertex on the path (a back edge) is a cycle; or use Kahn's and check if all V get ordered.

Common doubts

You must distinguish a vertex still open on the path (back edge = cycle) from a fully-finished vertex (a harmless shared descendant).
Vertices in a cycle never reach in-degree 0, so the algorithm orders fewer than V vertices.
Both are O(V+E). DFS also easily recovers the actual cycle; Kahn's also yields a topological order when acyclic.

Interview follow-ups

Keep a parent map and, on finding a back edge, walk from the current vertex back to the ancestor.
A prerequisite graph is completable iff it has no directed cycle.

Fun facts

  • Back edges in a DFS tree are precisely the cycle-creating edges of a directed graph.
  • The three-colour (white/grey/black) DFS is the CLRS formulation of this test.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: V = 3, edges = [[0,1],[1,2],[2,0]]
Output: true
0→1→2→0 is a directed cycle.
Example 2
Input: V = 4, edges = [[0,1],[0,2],[1,3],[2,3]]
Output: false
A diamond re-reaches 3 via two paths but has no cycle.
Constraints

- 1 <= V <= 10^5 - 0 <= edges.length <= 10^5 - edges are directed u -> v - no self-loops or duplicate edges

Solve this problem →