Tutorialspoint
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)
GraphAlgorithmsKPMGLTIMindtree
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Convert the edges list to an adjacency list representation of the graph

 Step 2: Create two boolean arrays: one to track visited nodes and another to track nodes in the current recursion stack
 Step 3: Implement a DFS function that marks nodes as visited and adds them to the recursion stack
 Step 4: For each neighbor of the current node, if it's not visited, recursively call DFS
 Step 5: If a neighbor is already in the recursion stack, a cycle is detected
 Step 6: After exploring all neighbors, remove the current node from the recursion stack
 Step 7: Run the DFS from each unvisited node to handle disconnected components

Submitted Code :