Find Eventual Safe States

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

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 is a terminal node itself).

Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.

Examples

Example 1:

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

Output: [2,4,5,6]

Explanation: Nodes 5 and 6 are terminal nodes (no outgoing edges). Node 2 leads to node 5 (safe). Node 4 leads to node 5 (safe). Nodes 0, 1, and 3 are part of a cycle 0 -> 1 -> 3 -> 0, so they are not safe.

Example 2:

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

Output: [4]

Explanation: Only node 4 is a terminal node. Nodes 0, 1, 2, and 3 are all part of cycles or lead to cycles, so the only safe node is node 4.

Example 3:

Input: graph = [[],[0,2,3,4],[3],[4],[]]

Output: [0,1,2,3,4]

Explanation: Node 0 and node 4 are terminal nodes. All other nodes eventually lead to terminal nodes only, so every node is safe.

Constraints

  • n == graph.length
  • 1 <= n <= 10000
  • 0 <= graph[i].length <= n
  • 0 <= graph[i][j] <= n - 1
  • graph[i] is sorted in strictly increasing order
  • The graph may contain self-loops
  • The number of edges in the graph will be in the range [1, 4 * 10000]
Source: Topological Sort pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle