Skip to content

Find Eventual Safe States

Find the nodes from which every path ends at a dead end, by peeling safe nodes backward from the terminals.

MediumTopological Sort
Solve on LeetCode

The problem

You get a directed graph as graph, where graph[i] lists the nodes that node i has edges to. A terminal node has no outgoing edges, and a node is safe when every path starting from it ends at a terminal node. Return all safe nodes in increasing order.

Input graph = [[1, 2], [3], [3], [], [5], [4]]

Output [0, 1, 2, 3]

3 is terminal, 1 and 2 lead only to 3, and 0 leads only to 1 and 2. Nodes 4 and 5 point at each other forever.

Input graph = [[0], [2], []]

Output [1, 2]

Node 0 has an edge to itself, so a path from it can loop forever. Node 1 always ends at the terminal node 2.

Key constraint: The graph can contain cycles and self-loops, and a node is unsafe exactly when some path from it reaches a cycle.

How to spot the pattern

  • A node's status depends on the status of every node it points to.
  • Cycles make nodes bad, and you can settle nodes one at a time in dependency order.

The idea

A terminal node is safe, and any node becomes safe once every edge leaving it is known to lead to a safe node. That is topological sort run backwards: start a queue with the terminal nodes, and each time a node is confirmed safe, lower the count of unconfirmed edges of every node that points to it. Nodes on a cycle, or with a path into one, always keep at least one unconfirmed edge, so they are never marked safe.

Brute force: Repeatedly sweep all nodes and mark a node safe once all of its targets are safe, until a sweep changes nothing, which can take O(V * (V + E)) time.

Step by step

  1. 1For each node, count its outgoing edges and record which nodes point to it.
  2. 2Put every node with no outgoing edges in a queue, since terminal nodes are safe.
  3. 3Take a safe node from the queue and, for each node pointing to it, lower that node's count of unconfirmed edges.
  4. 4When a count reaches 0, every edge of that node leads to safety, so mark it and add it to the queue.
  5. 5Return the safe nodes in increasing order.

See the pattern move

The topological sort pattern on a small example. Step through it, or press play.

Code

from collections import deque


class Solution:
    def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
        n = len(graph)
        points_here = [[] for _ in range(n)]        # v -> nodes with an edge into v
        unconfirmed = [len(nxt) for nxt in graph]   # edges not yet known to lead to safety
        for u in range(n):
            for v in graph[u]:
                points_here[v].append(u)

        queue = deque(u for u in range(n) if unconfirmed[u] == 0)  # terminal nodes are safe
        safe = [False] * n
        while queue:
            v = queue.popleft()
            safe[v] = True
            for u in points_here[v]:
                unconfirmed[u] -= 1
                if unconfirmed[u] == 0:  # every edge of u leads to a safe node
                    queue.append(u)

        return [u for u in range(n) if safe[u]]

Complexity

Time

O(V + E)

Space

O(V + E)

Every node enters the queue at most once and every edge is used once from each side; the reversed lists hold all E edges.

Watch out for

  • Calling a node safe because one path from it ends at a terminal node: every path has to.
  • Missing self-loops, such as node 0 pointing to itself, which make a node unsafe.
  • Returning the nodes in the order they were found instead of in increasing order.

Follow-up questions

Can you solve it with DFS instead?

Color nodes as unvisited, on the current path or finished. A node is unsafe if its DFS meets a node on the current path or an unsafe node, and safe otherwise. It is also O(V + E).

How is this related to Course Schedule?

Both settle a node once everything it depends on is settled. Here a node depends on the nodes it points to, so you run Kahn's algorithm on the reversed edges.

In Hinglish

Terminal nodes safe hain. Edges ko ulta dekho: jis node ke saare outgoing edges safe nodes tak jaate hain, woh bhi safe hai. Cycle waale nodes kabhi safe nahi banenge.

Related problems