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.length1 <= n <= 10^40 <= graph[i].length <= n0 <= graph[i][j] <= n - 1graph[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].See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI