MediumDepth-First SearchBreadth-First SearchGraphTopological Sort

1 approach, code in every language

Problem description

You are given a directed graph with n nodes labeled 0 to n - 1, described by an adjacency list graph, where graph[i] lists all nodes reachable from node i in one step. A node with no outgoing edges is called terminal.

A node is safe if every walk that starts at it is guaranteed to reach a terminal node after a finite number of steps, no matter which edges are chosen. Equivalently, a node is safe only if none of its walks can get trapped in a cycle.

Return an array containing all safe nodes, sorted in ascending order.

Example 1

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

Output: [2,4,5,6]

Nodes 5 and 6 are terminal. Nodes 2 and 4 only lead into node 5, so every path ends. Nodes 0, 1, 3 can enter the cycle 0 -> 1 -> 3 -> 0 area and are unsafe.

Example 2

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

Output: [4]

Only node 4 is terminal, and every other node can reach a cycle, so 4 is the single safe node.

Constraints

  • n == graph.length
  • 1 <= n <= 10^4
  • 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 is in the range [1, 4 * 10^4].

After the pattern

Now solve one you haven't seen.

States From Which the Batch Always Halts is our own problem on the technique behind Find Eventual Safe States: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free