
Problem
Solution
Submissions
Cycle in a Directed Graph
Certification: Intermediate Level
Accuracy: 100%
Submissions: 1
Points: 10
Write a C++ program to detect if a directed graph contains a cycle. The graph will be represented as an adjacency list where graph[i] contains a list of nodes that node i has an outgoing edge to.
Example 1
- Input: n = 4, edges = [[0,1], [1,2], [2,0], [3,1]]
- Output: true
- Explanation: There is a cycle in the graph: 0 → 1 → 2 → 0
Example 2
- Input: n = 3, edges = [[0,1], [1,2], [0,2]]
- Output: false
- Explanation: There is no cycle in the graph. The edges form a directed acyclic graph (DAG).
Constraints
- 1 ≤ n ≤ 10^4
- 0 ≤ edges.length ≤ 10^4
- edges[i].length == 2
- 0 ≤ edges[i][0], edges[i][1] < n
- All pairs (edges[i][0], edges[i][1]) are distinct
- Time Complexity: O(V+E) where V is the number of vertices and E is the number of edges
- Space Complexity: O(V)
Editorial
My Submissions
All Solutions
| Lang | Status | Date | Code |
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code |
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Use depth-first search (DFS) to traverse the graph
- Keep track of visited nodes and nodes currently in the recursion stack
- If a node is already in the recursion stack and visited again, a cycle exists
- Implement recursive DFS to explore all possible paths
- An alternative approach is to use Kahn's algorithm for topological sorting