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.

Input & Output

Example 1 — Basic Graph with Cycle
$ Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
💡 Note: Node 0: leads to cycle 0→1→2→5→0, so unsafe. Node 1: leads to same cycle, unsafe. Node 2: leads to node 5 (terminal), so safe. Node 3: leads to cycle, unsafe. Node 4: leads to node 5 (terminal), safe. Nodes 5,6: terminal nodes, safe.
Example 2 — Simple Linear Graph
$ Input: graph = [[1,2,3,4],[1,2],[3],[4],[]]
Output: [4]
💡 Note: Only node 4 is terminal (no outgoing edges). All paths from nodes 0,1,2,3 eventually lead to cycles or unsafe states. Only node 4 is guaranteed safe.
Example 3 — All Terminal Nodes
$ Input: graph = [[],[],[]]
Output: [0,1,2]
💡 Note: All nodes are terminal (no outgoing edges), so all nodes are safe by definition.

Constraints

  • n == graph.length
  • 1 ≤ n ≤ 104
  • 0 ≤ graph[i].length ≤ n
  • 0 ≤ graph[i][j] ≤ n - 1
  • graph[i] is sorted in a strictly increasing order

Visualization

Tap to expand
Find Eventual Safe States INPUT Directed Graph (7 nodes) 0 1 2 3 4 5 6 = Terminal/Safe = In cycle (unsafe) graph = [[1,2],[2,3],[5],[0],[5],[],[]] Nodes 5,6 are terminals 0-->1-->3-->0 forms cycle ALGORITHM STEPS 1 Reverse Graph Flip all edge directions 2 Count Out-degrees Track edges leaving each node 3 Initialize Queue Add terminal nodes (deg=0) 4 BFS Processing Propagate safe status back Topological Order: Queue: [5,6] --> [6,2,4] --> [2,4] --> [4] --> [] Nodes 0,1,3 never reach deg=0 Initial degrees: [2,2,1,1,1,0,0] Safe nodes have degree-->0 Cycle nodes stay positive FINAL RESULT Safe Nodes Highlighted 0 1 2 3 4 5 6 CYCLE = Safe node = Unsafe (in cycle) OUTPUT [2, 4, 5, 6] Key Insight: Reverse the graph and use topological sort! Terminal nodes (no outgoing edges) become sources. Process backwards: if all successors of a node are safe, that node is also safe. Nodes remaining in cycles never reach out-degree 0 and are therefore unsafe. TutorialsPoint - Find Eventual Safe States | Reverse Graph + Topological Sort
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
125.0K Views
Medium Frequency
~25 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen