As reported: Amazon SDE 1 interview (May 2025), the first of two questions — Find Eventual Safe States with tweaked wording; the second was Search in Rotated Sorted Array.
There is a directed graph of n nodes labelled 0 … n−1; graph[i] lists the nodes i has edges to. A terminal node has no outgoing edges. A node is safe if every possible path starting from it leads to a terminal node (or another safe node). Return all safe nodes in ascending order.
This is LeetCode 802 — Find Eventual Safe States.
Example 1
graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Nodes 0, 1 and 3 can loop forever (0 → 1 → 3 → 0).
Example 2
graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]
Output: [4]
Constraints: 1 ≤ n ≤ 10⁴; 0 ≤ graph[i].length ≤ n; at most 4 · 10⁴ edges; no duplicate edges in a list; self-loops are possible.
Code runner format: one line: graph as a JSON array of arrays (LeetCode's test-case format). Implement eventualSafeNodes(graph); the harness prints the safe nodes as a JSON array.