Skip to main content
Back to problems
#802
Medium Algorithms

Find eventual safe states

Depth-First Search Breadth-First Search Graph Theory Topological Sort
70.3% acceptance
Feb 22, 2026
6975
524
There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i]. A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node). Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn eventual_safe_nodes(graph: Vec<Vec<i32>>) -> Vec<i32> {
    let n = graph.len();
    // 0=unvisited, 1=visiting(on stack), 2=safe
    let mut state = vec![0u8; n];
    fn dfs(node: usize, graph: &Vec<Vec<i32>>, state: &mut Vec<u8>) -> bool {
      if state[node] == 2 { return true; }
      if state[node] == 1 { return false; }
      state[node] = 1;
      for &nb in &graph[node] {
        if !dfs(nb as usize, graph, state) {
          return false;
        }
      }
      state[node] = 2;
      true
    }
    (0..n).filter(|&i| dfs(i, &graph, &mut state)).map(|i| i as i32).collect()

  }
}