SDE & MLE Prep

802. Find Eventual Safe States

Problem

graph[i] lists the directed edges out of node i. A terminal node has no outgoing edges; a node is safe if every path starting from it ends at a terminal node. Return all safe nodes in ascending order.

Example: [[1,2],[2,3],[5],[0],[5],[],[]] → [2,4,5,6]

Constraints: n ≤ 10⁴.

A node is safe iff no path from it reaches a cycle. Three-color DFS: 0 = unvisited, 1 = on stack, 2 = safe. Reaching a node with color 1 means a cycle → unsafe. (Alternatively: Kahn's on the reversed graph.)

Complexity: O(V + E).

class Solution:
    def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
        color = [0] * len(graph)

        def safe(u):
            if color[u]:
                return color[u] == 2
            color[u] = 1
            if all(safe(v) for v in graph[u]):
                color[u] = 2
                return True
            return False          # stays 1 -> unsafe

        return [u for u in range(len(graph)) if safe(u)]