Cycle Detection in Graph - Problem

Given a directed graph represented as an adjacency list, determine if the graph contains a cycle using Depth-First Search (DFS) and the coloring technique.

In the coloring technique:

  • WHITE (0): Node not visited yet
  • GRAY (1): Node currently being processed (in DFS stack)
  • BLACK (2): Node completely processed (DFS finished)

A cycle exists if during DFS traversal, we encounter a GRAY node (indicating a back edge to an ancestor in the current DFS path).

Input: Adjacency list representation of a directed graph as a 2D array where graph[i] contains all nodes that node i points to.

Output: Return true if the graph contains a cycle, false otherwise.

Input & Output

Example 1 — Graph with Cycle
$ Input: graph = [[1],[2],[0]]
Output: true
💡 Note: Graph has nodes 0→1→2→0 forming a cycle. Node 0 points to 1, node 1 points to 2, node 2 points back to 0.
Example 2 — Acyclic Graph
$ Input: graph = [[1],[2],[]]
Output: false
💡 Note: Graph is 0→1→2 with no back edges. Node 2 has no outgoing edges, so no cycle exists.
Example 3 — Self Loop
$ Input: graph = [[0]]
Output: true
💡 Note: Node 0 points to itself, creating a self-loop which is a cycle of length 1.

Constraints

  • 1 ≤ graph.length ≤ 104
  • 0 ≤ graph[i].length ≤ 104
  • 0 ≤ graph[i][j] < graph.length
  • graph[i][j] != i (no self-loops except in test cases)
  • All edges are unique

Visualization

Tap to expand
INPUT GRAPHDFS ALGORITHMRESULT012Adjacency List:0 --> [1]1 --> [2]2 --> [0]1Start DFS from node 02Mark 0 as GRAY3Visit neighbor 1, mark GRAY4Visit neighbor 2, mark GRAYNode 2 tries to visit 00 is GRAY --> CYCLE!CYCLE DETECTEDOutput: truePath: 0 --> 1 --> 2 --> 0Back edge found from 2 to 0Key Insight:The moment we encounter a GRAY node during DFS, we've found a back edge indicating a cycle.TutorialsPoint - Cycle Detection in Graph | DFS Three-Color Algorithm
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
73.3K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen