Find Eventual Safe States Problem
Description
LeetCode Problem 802.
There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].
A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node.
Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.
Example 1:
Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Explanation: The given graph is shown above.
Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.
Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.
Example 2:
Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]
Output: [4]
Explanation:
Only node 4 is a terminal node, and every path starting at node 4 leads to node 4.
Constraints:
- n == graph.length
- 1 <= n <= 10^4
- 0 <= graph[i].length <= n
- 0 <= graph[i][j] <= n - 1
- graph[i] is sorted in a strictly increasing order.
- The graph may contain self-loops.
- The number of edges in the graph will be in the range [1, 4 * 10^4].
Solution
Approach: Topological Sort on the Reversed Graph
A node is unsafe exactly when some path from it reaches a cycle, since that path can go around the cycle forever. Every other node is safe. We can find the safe nodes by working backwards from the terminal nodes, the way Kahn's algorithm peels a graph:
- A terminal node (no outgoing edges) is safe.
- A node is safe once all of its outgoing edges lead to safe nodes.
So count for each node how many of its edges are not yet known to lead to a safe node (start with its out-degree), and build the reversed edges, incoming[v], so we can find the nodes pointing to v.
- Put every terminal node in a queue.
- Pop a node
vand mark it safe. For eachuinincoming[v], decreaseu's count by one. If it reaches zero, all ofu's edges lead to safe nodes, so pushu. - When the queue is empty, the marked nodes are exactly the safe ones. Collect them by scanning
0..n-1, which gives ascending order without sorting.
A node on a cycle, or with an edge into a cycle, never reaches a count of zero: its edge toward the cycle points to a node that is never marked safe. A self-loop is a cycle of length one, so that node is unsafe too.
This is iterative, so a long chain of 104 nodes causes no deep recursion. (A DFS that colors nodes white, gray and black also works and has the same complexity.)
Complexity: O(n + e) time and space, where n is the number of nodes and e the number of edges.
import collections
class Solution:
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
n = len(graph)
out_degree = [len(edges) for edges in graph] # edges not yet known to lead to a safe node
incoming = [[] for _ in range(n)] # incoming[v] = nodes with an edge to v
for u in range(n):
for v in graph[u]:
incoming[v].append(u)
# Terminal nodes are safe. Peel them off; a node becomes safe once all its edges lead to safe nodes.
queue = collections.deque(u for u in range(n) if out_degree[u] == 0)
safe = [False] * n
while queue:
v = queue.popleft()
safe[v] = True
for u in incoming[v]:
out_degree[u] -= 1
if out_degree[u] == 0:
queue.append(u)
return [u for u in range(n) if safe[u]] # already in ascending order
Now write it from memory
Close the write-up and solve it yourself against the tests.