1062. Find Eventual Safe States

MediumGraphsDFSGraphCycle

Given a directed graph as an adjacency list 'graph' (graph[i] lists nodes reachable from i in one step), a node is safe if every path starting from it leads to a terminal node (one with no outgoing edges) — that is, it cannot reach a cycle. Return all safe nodes sorted in ascending order. The input is JSON {graph}.

Input: JSON {graph}.

Output: Array — the sorted safe nodes.

Examples

Example 1
Input: {"graph":[[1,2],[2,3],[5],[0],[5],[],[]]}
Output: [2,4,5,6]
Explanation: These nodes avoid all cycles.
Example 2
Input: {"graph":[[]]}
Output: [0]
Explanation: A terminal node is safe.
Example 3
Input: {"graph":[[1],[0]]}
Output: []
Explanation: Both are in a cycle.

Constraints

Asked by

AmazonGoogleBloombergMicrosoftMeta
Solve this problem in the editor →