Find Eventual Safe States

Medium Topics Company Tags

The directed graph has nodes numbered from 0 through n-1. Each list graph[i] contains the destinations of outgoing edges from node i. A terminal node has no outgoing edges. A node is safe if every possible sequence of outgoing moves from it eventually ends at a terminal node. Thus a node is unsafe if it can reach a directed cycle, including a self-loop. Return all safe node numbers in increasing order. Terminal nodes themselves are safe.

Example 1:

Find Eventual Safe States, example 1: illustration of the example

Input: graph = [[1],[2],[]]

Output: [0,1,2]

Explanation: Node 2 is terminal. Node 1 can only move to 2, and node 0 can only move through 1 to 2. All three nodes are safe.

Example 2:

Find Eventual Safe States, example 2: illustration of the example

Input: graph = [[1],[0],[]]

Output: [2]

Explanation: Nodes 0 and 1 form a directed cycle, so neither is safe. Node 2 has no outgoing edges and is safe, giving [2].

Example 3:

Find Eventual Safe States, example 3: illustration of the example

Input: graph = [[0,1],[]]

Output: [1]

Explanation: Node 0 can move to terminal node 1, but it can also follow its self-loop forever. Because every possible path must end, node 0 is unsafe. Only node 1 is safe.

Constraints:

  • 1 <= n <= 10000
  • Each adjacency list contains between 0 and n node numbers, sorted in strictly increasing order.
  • Each node number is between 0 and n-1.
  • The total number of directed edges is between 1 and 40000.
  • Self-loops are allowed.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.