2Brute2Best
🔥0
02

Cycle detection / feasibility (Topological Sort Sub-pattern)

Decide whether an order exists at all, or which nodes can never reach a cycle.

Signals in the problem statement
  • ›

    "is it possible to finish all courses?"

  • ›

    "detect a cycle in a directed graph"

  • ›

    "safe nodes": every path ends at a terminal node

What makes it different

Course Schedule only asks whether Kahn places all n nodes. Detect Cycle uses the three-colour DFS: an edge into a grey node. Eventual Safe States reverses every edge and runs Kahn from the terminal nodes: a node is safe when all its out-edges lead to safe nodes, so nodes that merely lead into a cycle are unsafe too.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Course Schedule
    Basic Anchor·LeetCode #207
    Medium
  2. 2
    Detect Cycle in a Directed Graph
    Basic Reinforcement·GeeksforGeeks
    Medium
  3. 3
    Find Eventual Safe States
    Slight Variation·LeetCode #802
    Medium

Template

cycle-dfs-template.cpp
// Directed cycle check with three colours: 0 = not seen, 1 = on the current path, 2 = finished.
bool dfsCycle(int u, const vector<vector<int>>& adj, vector<int>& color) {
    color[u] = 1;
    for (int v : adj[u]) {
        if (color[v] == 1) return true;           // back edge to the current path: a cycle
        if (color[v] == 0 && dfsCycle(v, adj, color)) return true;
    }
    color[u] = 2;                                 // every path from u is cycle-free
    return false;
}

bool hasCycle(int n, const vector<vector<int>>& edges) {
    vector<vector<int>> adj(n);
    for (auto& e : edges) adj[e[0]].push_back(e[1]);
    vector<int> color(n, 0);
    for (int u = 0; u < n; u++)
        if (color[u] == 0 && dfsCycle(u, adj, color)) return true;
    return false;
}
Remember this · Topological Sort
Trigger
Prerequisites, dependencies, build order, "can all courses be finished?", ordering letters from sorted words.
Think
Is this a directed graph where some things must happen before others?
Key question
Which nodes currently have in-degree 0?