 All Problems
Find Eventual Safe States
medium
topological sort
graph
dfs
google
amazon

There is a directed graph with n nodes. A node is a terminal node if it has no outgoing edges. A node is safe if every path starting from that node eventually leads to a terminal node.

Return an array of all safe nodes in sorted order.

Example 1:

Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]

Constraints:

  • n == graph.length
  • 1 <= n <= 10^4
  • 0 <= graph[i].length <= n
Run to check your code against the sample cases, or submit to run every case