Bird
Raised Fist0

What is the subtle bug?

medium🐞 Bug Identification Q7 of Q15
Topological Sort - Parallel Courses (Minimum Semesters)
The following code attempts to compute the minimum semesters to complete all courses using BFS topological sort. What is the subtle bug? ```python from collections import deque, defaultdict def min_semesters_buggy(n, relations): graph = defaultdict(list) indegree = [0] * n for u, v in relations: graph[u].append(v) indegree[v] += 1 queue = deque([i for i in range(n) if indegree[i] == 0]) semester = 0 processed = 0 while queue: semester += 1 for _ in range(len(queue)): course = queue.popleft() processed += 1 for nei in graph[course]: indegree[nei] -= 1 if indegree[nei] == 0: queue.append(nei) return semester if processed == n else -1 ```
AIndegree array is initialized with size n instead of n+1, causing index errors for 1-based courses
BQueue is not initialized with courses having zero indegree
CProcessed counter is not incremented inside the loop
DSemester counter is incremented inside the inner loop instead of outer loop
Step-by-Step Solution
Solution:
  1. Step 1: Check indexing assumptions

    Courses are labeled 1 to n, but indegree array is size n with 0-based indexing, causing off-by-one errors.
  2. Step 2: Consequences of wrong indexing

    Accessing indegree[v] where v ≥ n causes index errors or incorrect indegree updates, breaking the algorithm.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Indegree array size must match course labeling [OK]
Quick Trick: Check indexing matches course labels (0-based vs 1-based) [OK]
Common Mistakes:
MISTAKES
  • Ignoring 1-based indexing
  • Assuming zero-based indexing without adjustment
Trap Explanation:
PITFALL
  • Candidates often overlook indexing mismatch, causing subtle bugs that pass some tests.
Interviewer Note:
CONTEXT
  • Tests attention to indexing details and off-by-one errors in graph problems.
Master "Parallel Courses (Minimum Semesters)" 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