Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Detect Cycle in Directed Graph (DFS)

Medium Acceptance 67.67% Points 30.00

You are given a directed graph with V vertices and its adjacency list. Your task is to determine whether the graph contains a cycle using Depth First Search (DFS).

Return true if a cycle exists; otherwise, return false.

Examples
Example 1

image Input: V = 3, edges = [[0,1],[1,2],[2,0]]
Output: true
Explanation: The directed graph contains a cycle.

Example 2

image Input: V = 4, edges = [[0,1],[1,2],[2,3]]
Output: false
Explanation: The directed graph is acyclic.

Example 3

image Input: V = 1, edges = []
Output: false
Explanation: The graph contains no cycle.

Constraints
    • 1 = V = 105
    • 0 = E = 2 × 105
Companies
ZScaler
Topics
Graph
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions