Bird
Raised Fist0

Consider the following buggy code snippet for topological sort positions. Which line contains the subtle bug that can cause incorrect matrix construction?

medium🐞 Bug Identification Q14 of Q15
Topological Sort - Build a Matrix With Conditions
Consider the following buggy code snippet for topological sort positions. Which line contains the subtle bug that can cause incorrect matrix construction?
ALine where graph[u].append(v) is called
BLine where queue is initialized with nodes of zero in-degree
CLine where pos[node] is assigned idx
DLine where in_degree[u] is incremented instead of in_degree[v]
Step-by-Step Solution
  1. Step 1: Identify how in-degree is updated

    In-degree should count incoming edges; incrementing in_degree[u] is incorrect because u is the source, not the target.
  2. Step 2: Understand impact of bug

    Incorrect in-degree counts cause wrong zero in-degree nodes, breaking topological order and matrix correctness.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Correct in-degree update is critical for cycle detection and ordering [OK]
Quick Trick: In-degree counts incoming edges, not outgoing [OK]
Common Mistakes:
MISTAKES
  • Mixing source and target when updating in-degree
  • Assuming graph edges are undirected
Trap Explanation:
PITFALL
  • Incrementing in-degree of source node looks plausible but breaks ordering logic subtly.
Interviewer Note:
CONTEXT
  • Tests attention to detail and understanding of graph in-degree semantics.
Master "Build a Matrix With Conditions" 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