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 StatesInput: [[1,2],[2,3],[5],[0],[5],[],[]] → Output: [2,4,5,6]0123456Unsafe (In Cycle)Nodes: 0, 1, 3Safe NodesNodes: 2, 4, 5, 6Cycle Detected0 → 1 → 2 → 5, 3 → 0
Understanding the Visualization
1
Input Graph
Directed graph with potential cycles
2
Cycle Detection
Find nodes that are part of or lead to cycles
3
Safe Nodes
Nodes that only lead to terminal nodes
Key Takeaway
🎯 Key Insight: Safe nodes never lead to cycles - use DFS with state tracking or reverse graph topology
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