Find Eventual Safe States

A directed graph of n nodes (0 to n - 1) is given as an adjacency list graph, where graph[i] lists the nodes that node i has edges to. A terminal node has no outgoing edges. A node is safe if every path that starts at it ends at a terminal node (or at another safe node). Return all safe nodes in ascending order.

30:00

Find Eventual Safe States
medium
Free written solution
Topics
Companies

A directed graph of n nodes (0 to n - 1) is given as an adjacency list graph, where graph[i] lists the nodes that node i has edges to. A terminal node has no outgoing edges. A node is safe if every path that starts at it ends at a terminal node (or at another safe node). Return all safe nodes in ascending order.

Example 1:
Input: {"graph":[[1,2],[2,3],[5],[0],[5],[],[]]}
Output: [2,4,5,6]
Constraints:
  • n==graph.lengthn == \text{graph.length}

  • 1≤n≤1041 \leq n \leq 10^4

  • 0≤graph[i].length≤n0 \leq \text{graph}[i].\text{length} \leq n

  • 0≤graph[i][j]≤n−10 \leq \text{graph}[i][j] \leq n - 1

  • graph[i]\text{graph}[i] is sorted in strictly increasing order.

  • The graph may contain self-loops.

  • The number of edges is in the range [1,4×104][1, 4 \times 10^4].

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"graph":[[1,2],[2,3],[5],[0],[5],[],[]]}

Each of the 7 nodes must be judged: a node is safe only if no path from it can loop forever.

0123456

DFS stack

empty

safe nodes (answer, ascending)

[]

not visited (0)
on DFS stack (1)
unsafe (stays 1)
safe (2)
Variables
VariableValue
stackempty
safe0
DepthFunction Call
Stack empty
0/38