Bird
Raised Fist0

Identify the subtle bug: ```python for u in range(n): for v in graph[u]: reverse_graph[u].append(v) in_degree[u] = len(graph[u]) ```

medium🐞 Bug Identification Q7 of Q15
Topological Sort - Find Eventual Safe States
The following code attempts to find eventual safe states using the reversed graph and Kahn's algorithm. Identify the subtle bug: ```python for u in range(n): for v in graph[u]: reverse_graph[u].append(v) in_degree[u] = len(graph[u]) ```
Ain_degree should count incoming edges, not outgoing edges
Breverse_graph is built incorrectly; edges should be reversed as reverse_graph[v].append(u)
Cin_degree initialization is correct but queue initialization is missing
DThe loop should iterate over reverse_graph instead of graph
Step-by-Step Solution
Solution:
  1. Step 1: Check reverse graph construction

    Edges must be reversed: for edge u->v, reverse_graph[v].append(u) to track predecessors.
  2. Step 2: Identify bug in code

    Current code appends v to reverse_graph[u], which does not reverse edges, breaking the algorithm.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Correct reversed graph is essential for Kahn's algorithm [OK]
Quick Trick: Reverse edges: reverse_graph[v].append(u) [OK]
Common Mistakes:
MISTAKES
  • Confusing direction when building reversed graph
  • Misusing in-degree counts
Trap Explanation:
PITFALL
  • Many candidates build reverse graph incorrectly, causing wrong safe node detection.
Interviewer Note:
CONTEXT
  • Tests attention to detail in graph reversal and in-degree calculation.
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