Bird
Raised Fist0

Suppose the course prerequisites can form multiple disconnected subgraphs and some courses have no prerequisites. How should Kahn's Algorithm be modified to return a valid order including all courses?

hard🎤 Interviewer Follow-up Q15 of Q15
Topological Sort - Course Schedule II (Topological Order)
Suppose the course prerequisites can form multiple disconnected subgraphs and some courses have no prerequisites. How should Kahn's Algorithm be modified to return a valid order including all courses?
AInitialize the queue with all nodes having zero in-degree, including those in disconnected components.
BUse backtracking to try all permutations since BFS cannot handle disconnected graphs.
CRun DFS from each node separately and concatenate results without cycle checks.
DStart BFS from any arbitrary node and ignore disconnected components.
Step-by-Step Solution
Solution:
  1. Step 1: Identify disconnected components

    Courses with no prerequisites form disconnected subgraphs with zero in-degree nodes.
  2. Step 2: Initialize queue with all zero in-degree nodes

    Queue must include all such nodes to process all components and produce a full valid order.
  3. Step 3: Process BFS as usual

    Processing all zero in-degree nodes ensures all courses are included in the order.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Queue initialization with all zero in-degree nodes covers disconnected graphs [OK]
Quick Trick: Queue must start with all zero in-degree nodes, not just one [OK]
Common Mistakes:
MISTAKES
  • Starting BFS from a single node only
  • Ignoring disconnected components
  • Skipping cycle detection in DFS
Trap Explanation:
PITFALL
  • Starting BFS from one node misses disconnected parts; backtracking is too slow and unnecessary.
Interviewer Note:
CONTEXT
  • Tests if candidate understands handling disconnected graphs in topological sort.
Master "Course Schedule II (Topological Order)" 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