Skip to problem
←

Find Eventual Safe States

Medium 0 attempts

A terminal vertex has no outgoing edges. A vertex is eventually safe if every path starting there eventually reaches a terminal vertex. Equivalently, no directed cycle is reachable from it. Terminal vertices are themselves safe.

It is not enough to have one path to a terminal: if another choice leads to a cycle, the starting vertex is unsafe. Return the safe vertex indices in ascending order.

Function contract

graph is a directed adjacency list: vertices are 0 through graph.length - 1, and graph[u] lists the destinations of edges from u.

Output: Return all safe vertex indices in ascending order.

Example 1

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

Example 2

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

Explanation: Vertex 0 can stay in its self-loop forever. Vertex 1 is terminal and therefore safe.

Constraints
  • 1 <= n == graph.length <= 10^4
  • 0 <= graph[u].length <= n
  • Each neighbor is an integer in [0, n - 1]; adjacency lists contain no duplicates.
  • Self-loops and disconnected components are allowed.
Topics

Reverse Topological Elimination

Start with terminal vertices. Remove their incoming edges in the reversed graph; a predecessor is safe when every outgoing edge has been removed. Vertices trapped in or leading to cycles are never eliminated.

javascript
function eventualSafeNodes(graph) {
  const n = graph.length,
    reverse = Array.from({ length: n }, () => []),
    degree = graph.map((a) => a.length),
    queue = [];
  graph.forEach((edges, u) => edges.forEach((v) => reverse[v].push(u)));
  for (let u = 0; u < n; u++) if (degree[u] === 0) queue.push(u);
  for (let head = 0; head < queue.length; head++)
    for (const u of reverse[queue[head]]) if (--degree[u] === 0) queue.push(u);
  return degree.flatMap((d, u) => (d === 0 ? [u] : []));
}

Time: O(V + E) | Space: O(V + E)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript