← DiffPush

Detect Cycle in a Directed Graph

Standard Bar Graphs · Traversal Problems O(V + E) · O(V)

The Circular Approval Chain Alert

A workflow engine routes approval requests along one-way dependency edges between stages. A stage that must wait on a chain that eventually waits back on itself deadlocks the pipeline. The engine needs a one-shot audit: does the one-way dependency map contain any loop, no matter how deeply buried?

Input: An integer v (stages numbered 0..v-1) and an edge list edges where each entry [u, w] is a one-way dependency u -> w.

Output: Return true if the directed graph contains a cycle, otherwise false.

Constraints

Examples

Example 1

Input: {"v":4,"edges":[[0,1],[1,2],[2,0],[3,1]]}
Output: true
0 -> 1 -> 2 -> 0 is a closed loop of approvals.

Example 2

Input: {"v":4,"edges":[[0,1],[1,2],[2,3]]}
Output: false
A straight dependency chain never loops back.

Solve this in your browser →

Also on LeetCode ↗