Bird
Raised Fist0

Identify the line containing the subtle bug that causes incorrect results on graphs with cycles or repeated characters.

medium🐞 Bug Identification Q14 of Q15
Topological Sort - Longest Path With Different Adjacent Characters
The following code attempts to find the longest path with different adjacent characters in a DAG. Identify the line containing the subtle bug that causes incorrect results on graphs with cycles or repeated characters.
ALine with 'for node in topo_order:' loop
BLine with 'dp = [1] * n' initialization
CLine with 'if indegree[nei] <= 0:' condition
DLine with 'return max(dp)' statement
Step-by-Step Solution
  1. Step 1: Analyze indegree decrement and queue append

    The condition 'if indegree[nei] <= 0:' incorrectly allows nodes with negative indegree to be enqueued multiple times, breaking topological order.
  2. Step 2: Consequence of bug

    This causes incorrect topo_order and potentially infinite loops or wrong dp updates.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Correct condition should be 'indegree[nei] == 0' to enqueue once [OK]
Quick Trick: Check indegree condition carefully for cycle detection [OK]
Common Mistakes:
MISTAKES
  • Using <= 0 instead of == 0 for indegree check
  • Ignoring character difference in dp update
  • Incorrect dp initialization
Trap Explanation:
PITFALL
  • <= 0 looks safe but allows multiple enqueues, breaking topological order assumptions.
Interviewer Note:
CONTEXT
  • Tests candidate's attention to subtle cycle detection and queue management bugs.
Master "Longest Path With Different Adjacent Characters" 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