Find Eventual Safe States

Pattern: Cycle detection

medium

A node is safe when every path from it ends at a terminal node. Work backwards: terminal nodes are safe; a node becomes safe once all its outgoing edges lead to safe nodes. On the reversed graph this is Kahn's algorithm on out-degrees.

The problem

graph[i] lists the nodes node i points to. A terminal node has no outgoing edges; a safe node is one from which every path leads to a terminal node. Return all safe nodes in increasing order.

Think first

  • Which nodes are obviously safe?
  • When does a node become safe?
  • How do you notice 'all edges now lead to safe nodes' quickly?

Hints

    Brute force, and why it fails

    For each node, search all paths for a cycle: O(V × (V + E)).

    The key insight

    Peeling safe nodes from the terminal end, using reversed edges, decides every node in one pass.

    Dry run

    safe5 6

    graph [[1, 2], [2, 3], [5], [0], [5], [], []]. Terminal nodes 5 and 6 are safe.

    Step 1 of 3

    The plan

    out = out-degrees; queue = nodes with out 0
    while queue: v = pop; safe[v]
      for u with an edge u → v: out[u] -= 1; if 0: push u
    

    Complexity

    Time
    O(V + E)
    Space
    O(V + E)

    Each edge is reversed and processed once.

    Edge cases

    • A self-loop: that node is unsafe.
    • No edges: every node is safe.
    • One big cycle: none.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<Integer> eventualSafeNodes(int[][] graph) {
            int n = graph.length;
            List<List<Integer>> reverse = new ArrayList<>();
            for (int i = 0; i < n; i++) reverse.add(new ArrayList<>());
            int[] outDegree = new int[n];
            for (int u = 0; u < n; u++) {
                outDegree[u] = graph[u].length;
                for (int v : graph[u]) reverse.get(v).add(u);
            }
            Queue<Integer> q = new ArrayDeque<>();
            for (int i = 0; i < n; i++) if (outDegree[i] == 0) q.add(i);   // terminal nodes are safe
            boolean[] safe = new boolean[n];
            while (!q.isEmpty()) {                  // a node is safe once all its edges lead to safe nodes
                int v = q.poll();
                safe[v] = true;
                for (int u : reverse.get(v)) if (--outDegree[u] == 0) q.add(u);
            }
            List<Integer> out = new ArrayList<>();
            for (int i = 0; i < n; i++) if (safe[i]) out.add(i);
            return out;
        }
    }

    C++

    class Solution {
    public:
        vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
            int n = static_cast<int>(graph.size());
            vector<vector<int>> reverse(n);
            vector<int> outDegree(n);
            for (int u = 0; u < n; u++) {
                outDegree[u] = static_cast<int>(graph[u].size());
                for (int v : graph[u]) reverse[v].push_back(u);
            }
            queue<int> q;
            for (int i = 0; i < n; i++) if (outDegree[i] == 0) q.push(i);   // terminal nodes are safe
            vector<bool> safe(n, false);
            while (!q.empty()) {                    // a node is safe once all its edges lead to safe nodes
                int v = q.front();
                q.pop();
                safe[v] = true;
                for (int u : reverse[v]) if (--outDegree[u] == 0) q.push(u);
            }
            vector<int> out;
            for (int i = 0; i < n; i++) if (safe[i]) out.push_back(i);
            return out;
        }
    };

    Python

    from collections import deque
    
    class Solution:
        def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:
            n = len(graph)
            reverse = [[] for _ in range(n)]
            out_degree = [len(g) for g in graph]
            for u in range(n):
                for v in graph[u]:
                    reverse[v].append(u)
            q = deque(i for i in range(n) if out_degree[i] == 0)   # terminal nodes are safe
            safe = [False] * n
            while q:                                # a node is safe once all its edges lead to safe nodes
                v = q.popleft()
                safe[v] = True
                for u in reverse[v]:
                    out_degree[u] -= 1
                    if out_degree[u] == 0:
                        q.append(u)
            return [i for i in range(n) if safe[i]]

    Common mistakes

    • Marking a node safe because one of its edges is safe.
    • Forgetting to return the nodes sorted.

    Similar problems