Find Eventual Safe States

Given vertexCount vertices numbered 0 through vertexCount-1 and a directed adjacency list, return every eventual safe vertex in ascending order. A vertex is…

Given vertexCount vertices numbered 0 through vertexCount-1 and a directed adjacency list, return every eventual safe vertex in ascending order. A vertex is safe when every path starting there eventually reaches a vertex with no outgoing edges. Equivalently, no directed cycle is reachable from it. A terminal vertex and an isolated vertex are safe. Return an empty array if no vertex is safe.

- 1 <= vertexCount <= 10000 - adjacency has exactly vertexCount rows - 1 <= the total number of directed edges <= 40000 - Each row contains strictly increasing integer vertex IDs in 0..vertexCount-1 - Self-loops and disconnected components are allowed; duplicate neighbors are not - The preset visualizer uses at most 24 vertices and 48 directed edges; larger valid inputs remain execution-only

Example 1: input vertexCount = 6, adjacency = [[1,2],[3],[4],[1],[],[2]]; output [2,4,5]. Vertices 2 and 5 can only lead to terminal vertex 4. Vertices 1 and 3 form a cycle. Vertex 0 is unsafe even though one of its outgoing branches reaches 4, because its other branch reaches that cycle.

Example 2: input vertexCount = 4, adjacency = [[],[3],[0],[]]; output [0,1,2,3]. Every path terminates. The answer is sorted by vertex ID, not by the order in which a traversal discovers safety.

Category: Graphs. Topic: graph. Difficulty: Medium. Patterns: graph-traversal.