Safe nodes

Write codeMedium30 min

Your task

A directed graph has n nodes (labeled 0..n-1); graph[i] is the list of nodes i points to. A node is 'safe' if every possible path starting from it eventually reaches a terminal node (a node with no outgoing edges), equivalently, no path from it can ever enter a cycle. Return all safe nodes in ascending order.

Examples

eventual_safe_nodes(graph: list[list[int]]) -> list[int]
Example 1
Inputeventual_safe_nodes([[1, 2], [2, 3], [5], [0], [5], [], []])
Output[2, 4, 5, 6]