Detect Cycle in a Directed Graph
Problem Statement
You are given a directed graph with V nodes, numbered from 0 to V − 1, and a list of directed edges. Each edge [u, v] is an arrow from u to v.
Return true if the graph has a cycle. A cycle is a walk that follows the arrows and comes back to the node where it started. Return false if there is no such walk.
V, the number of nodes, and edges, a list of pairs [u, v] where u → v is an arrow.
true if the directed graph contains a cycle, otherwise false.
A straight chain 0 → 1 → 2 → 3. Following the arrows always moves forward, so no walk comes back.
The walk 0 → 1 → 2 → 0 returns to node 0, so there is a cycle. The arrow 2 → 3 is not part of it.
Two nodes with arrows both ways: 0 → 1 → 0 is a cycle.
- • Nodes are numbered from 0 to V − 1.
- • Every edge is directed: [u, v] is an arrow from u to v only.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each node s, search along the arrows; if the search reaches s again, there is a cycle
One DFS over the whole graph; an arrow into a grey node (on the current path) closes a cycle
A directed graph has a cycle exactly when some node can reach itself by following arrows. So for each node s, run a search from s along the arrows. If the search reaches s again, there is a cycle.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Topological Sort translate into production architectures and low-level memory mechanics.