FastPrepDetect a Cycle in a Directed Graph

Detect a Cycle in a Directed Graph

DeepInfra logoDeepInfra● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

You are given a directed graph with vertices numbered from 0 through numNodes - 1 and a list of directed edges. Return true if the graph contains at least one directed cycle; otherwise return false.

The graph may be disconnected. A self-loop is a cycle, and parallel edges must be processed independently.

Function

hasDirectedCycle(numNodes: int, edges: int[][]) → boolean

Examples

Example 1

numNodes = 4edges = [[0,1],[1,2],[2,0],[2,3]]return = true

The edges 0 to 1, 1 to 2, and 2 to 0 form a directed cycle.

Example 2

numNodes = 5edges = [[0,1],[1,2],[0,3],[3,4]]return = false

Every edge follows an acyclic ordering, so all five nodes can be removed topologically.

Constraints

  • 1 <= numNodes <= 200000
  • 0 <= edges.length <= 300000
  • edges[i].length == 2
  • 0 <= edges[i][0], edges[i][1] < numNodes
  • self-loops and parallel directed edges are allowed
See DeepInfra hiring insights
public boolean hasDirectedCycle(int numNodes, int[][] edges) {
    // Write your code here.
}
numNodes4
edges[[0,1],[1,2],[2,0],[2,3]]
expectedtrue
Checking account…