Find Eventual Safe States

Medium#802from the dead ends back

You get a directed graph: for each node, the list of nodes it has arrows to. A node with no arrows out is a dead end. A node is safe if every walk from it, whichever arrows it follows, ends at a dead end. Return all safe nodes in increasing order. Our example: 0 → [1, 3], 1 → [2, 5], 2 → [], 3 → [4], 4 → [6], 5 → [], 6 → [3, 5]. The answer is [1, 2, 5].

input
graph: a directed graph of n nodes numbered from 0; graph[i] are the nodes node i has arrows to. A node with no arrows out is a dead end.
returns
All safe nodes in increasing order. A node is safe if every walk from it, whichever arrows it follows, ends at a dead end.
constraints
  • n = graph.length, 1 ≤ n ≤ 400
  • 0 ≤ graph[i][j] < n
  • graph[i] is in strictly increasing order; a node may have an arrow to itself
  • 0 ≤ sum(graph[i].length) ≤ 2000
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[][]} graph
 * @return {number[]}
 */
function eventualSafeNodes(graph) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more topological sort problems

Pattern “Topological sort” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.