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 yetGRAY (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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code