Find Eventual Safe States (LeetCode 802): Solution and Explanation
Given a directed graph as an adjacency list, return every node from which all paths end at a terminal node (a node with no outgoing edges). Such nodes are called safe, and the answer lists them in ascending order.
Intuition
A path that never ends must go around a cycle forever. So a node is unsafe exactly when some path from it can reach a cycle, and safe when no path can.
A DFS finds cycles by noticing it has walked back onto a node that is still on its own stack. Give each node a color: 0 for unvisited, 1 for on the stack, 2 for proven safe.
When a cycle is found, every node on the stack can reach it, so all of them are unsafe. Leaving them colored 1 records that for later searches, and each node is decided only once.
Approach: DFS with three colors
- Create
color = [0] * n. - In
safe(u): ifcolor[u] > 0, returncolor[u] == 2. - Set
color[u] = 1, then for each neighbourv, ifsafe(v)is false return false right away, leavinguat 1. - If every neighbour was safe, set
color[u] = 2and return true. - Return every
ufrom 0 to n - 1 for whichsafe(u)is true. The loop runs in order, so the answer is already sorted.
Step-by-step example
graph = [[1,2],[2,3],[5],[0],[5],[],[]]
- safe(0) colors 0 with 1 and follows 0 -> 1. Node 1 is colored 1 and follows 1 -> 2, then 2 -> 5. Node 5 has no edges, so it becomes 2, and then 2 becomes 2.
- Back at 1, the next edge is 1 -> 3. Node 3 follows 3 -> 0, and 0 is still on the stack with color 1: a cycle. So 3, 1 and 0 are unsafe and stay at 1.
- The outer loop asks about 1, 2 and 3 next. They are already decided: 1 and 3 are unsafe, and 2 is safe.
- safe(4) follows 4 -> 5, which is safe, so 4 is safe. Node 6 has no edges and is safe. The answer is [2,4,5,6].
Code: Python, Java, C++
1class Solution:
2 def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
3 n = len(graph)
4 color = [0] * n # 0 new, 1 on stack or unsafe, 2 safe
5
6 def safe(u):
7 if color[u] > 0:
8 return color[u] == 2
9 color[u] = 1
10 for v in graph[u]:
11 if not safe(v):
12 return False
13 color[u] = 2
14 return True
15
16 return [u for u in range(n) if safe(u)]1class Solution {
2 public List<Integer> eventualSafeNodes(int[][] graph) {
3 int n = graph.length;
4 int[] color = new int[n];
5 List<Integer> ans = new ArrayList<>();
6 for (int u = 0; u < n; u++) {
7 if (safe(graph, color, u)) ans.add(u);
8 }
9 return ans;
10 }
11
12 private boolean safe(int[][] graph, int[] color, int u) {
13 if (color[u] > 0) return color[u] == 2;
14 color[u] = 1;
15 for (int v : graph[u]) {
16 if (!safe(graph, color, v)) return false;
17 }
18 color[u] = 2;
19 return true;
20 }
21}1class Solution {
2public:
3 vector<int> eventualSafeNodes(vector<vector<int>>& graph) {
4 int n = graph.size();
5 vector<int> color(n, 0);
6 vector<int> ans;
7 for (int u = 0; u < n; u++) {
8 if (safe(graph, color, u)) ans.push_back(u);
9 }
10 return ans;
11 }
12
13private:
14 bool safe(vector<vector<int>>& graph, vector<int>& color, int u) {
15 if (color[u] > 0) return color[u] == 2;
16 color[u] = 1;
17 for (int v : graph[u]) {
18 if (!safe(graph, color, v)) return false;
19 }
20 color[u] = 2;
21 return true;
22 }
23};Time and space complexity
O(n + e)
Each node gets its final color once, and each edge is followed at most once, where e is the number of edges.
O(n)
The color array and the recursion stack each hold at most n entries.
Other approaches
Reverse graph + Kahn's topological sort (time O(n + e), space O(n + e))
Reverse every edge and count each node's out-degree. Start a queue with the terminal nodes (out-degree 0). Each time a node is removed, lower the out-degree of its predecessors and enqueue any that reach 0. The nodes that get removed are exactly the safe ones. This avoids recursion.
DFS from every node separately (time O(n * (n + e)), space O(n))
For each node, run a fresh DFS that checks whether a cycle is reachable, without sharing results between searches. It is correct but repeats work, which is too slow at n = 10^4.
Common mistakes
- Resetting a node to 0 when the DFS leaves it after finding a cycle. It must stay unsafe, or later searches will redo work and may return the wrong result.
- Using a plain visited boolean. It cannot tell a node on the current stack (a cycle) apart from one already finished and proven safe.
- Forgetting self-loops. An edge u -> u is a cycle of length one, so u is unsafe.
- Deep recursion. A chain of 10^4 nodes exceeds Python's default recursion limit, so raise it or use the iterative Kahn approach.
Frequently asked questions
Why can nodes on the stack stay at color 1 forever?
When the DFS returns false, it has found a path from the current node to a cycle. Every node on the stack has a path to the current node, so all of them can reach that cycle too and are unsafe. Color 1 then means unsafe once the search has finished.
Is a terminal node safe?
Yes. A terminal node has no outgoing edges, so every path starting there ends immediately. In the DFS it has no neighbours to check and goes straight to color 2.
How is this related to cycle detection in Course Schedule?
It is the same three-color DFS. Course Schedule asks whether any cycle exists; this problem asks which nodes can avoid every cycle.
Why is the output already sorted?
The outer loop visits nodes 0, 1, 2 and so on, and appends a node only when it is safe, so the list is in ascending order.