Bird
Raised Fist0

Consider the following Python code implementing the optimal approach to find eventual safe states. Given the input graph = [[1],[2],[3],[]], what is the final returned list of safe nodes?

easy🧾 Code Trace Q12 of Q15
Topological Sort - Find Eventual Safe States
Consider the following Python code implementing the optimal approach to find eventual safe states. Given the input graph = [[1],[2],[3],[]], what is the final returned list of safe nodes?
from collections import deque

def eventualSafeNodes(graph):
    n = len(graph)
    reverse_graph = [[] for _ in range(n)]
    in_degree = [0] * n

    for u in range(n):
        for v in graph[u]:
            reverse_graph[v].append(u)
        in_degree[u] = len(graph[u])

    queue = deque([i for i in range(n) if in_degree[i] == 0])
    safe = []

    while queue:
        node = queue.popleft()
        safe.append(node)
        for prev in reverse_graph[node]:
            in_degree[prev] -= 1
            if in_degree[prev] == 0:
                queue.append(prev)

    return sorted(safe)
A[3]
B[0, 3]
C[0, 1, 2, 3]
D[1, 2, 3]
Step-by-Step Solution
Solution:
  1. Step 1: Initialize in-degree and reverse graph

    Graph has edges: 0->1, 1->2, 2->3, 3->none. So in_degree = [1,1,1,0], reverse_graph = [[],[0],[1],[2]].
  2. Step 2: Process queue starting with nodes having in-degree 0

    Start with node 3 in queue. Pop 3, safe=[3]. Decrement in_degree of 2 to 0, add 2 to queue. Pop 2, safe=[3,2]. Decrement in_degree of 1 to 0, add 1. Pop 1, safe=[3,2,1]. Decrement in_degree of 0 to 0, add 0. Pop 0, safe=[3,2,1,0].
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    All nodes lead to terminal node 3, so all are safe [OK]
Quick Trick: Nodes with zero out-degree start the safe node chain [OK]
Common Mistakes:
MISTAKES
  • Forgetting to sort final safe list
  • Miscounting in-degree initialization
  • Off-by-one errors in queue processing
Trap Explanation:
PITFALL
  • Some may think only terminal nodes are safe, ignoring nodes leading to terminal nodes.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to mentally execute BFS topological sort on reversed graph.
Master "Find Eventual Safe States" in Topological Sort

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Topological Sort Quizzes