Course Schedule (Topological Sort)

Algorithms
Medium
Oracle
27.4K views

Determine if you can finish all courses given an array of prerequisite pairs. Use graph traversal (BFS or DFS) to check for cycles.

Why Interviewers Ask This

Oracle interviewers use this problem to evaluate a candidate's ability to model real-world dependency systems as directed graphs. They specifically assess whether you can identify cycles, which represent impossible scheduling scenarios in academic or enterprise workflows. This tests your grasp of topological sorting, a fundamental concept for managing complex task dependencies efficiently.

How to Answer This Question

1. Clarify the input: Confirm if courses are numbered 0 to n-1 and how prerequisites map to edges. Oracle values precision, so ask about edge cases like isolated nodes or empty inputs immediately. 2. Choose a traversal strategy: Decide between Kahn's Algorithm (BFS with in-degree tracking) or DFS-based cycle detection. Explain your choice; BFS is often preferred for finding a valid order, while DFS is intuitive for pure cycle detection. 3. Define the data structures: Propose using an adjacency list for the graph and an array or hash map to track in-degrees for BFS, or a visited state array (unvisited, visiting, visited) for DFS. 4. Execute the logic: Walk through the algorithm step-by-step. For BFS, initialize the queue with zero in-degree nodes and process neighbors. For DFS, traverse deeply and backtrack if a 'visiting' node is encountered again. 5. Analyze complexity: Conclude by stating the time complexity is O(V + E) and space complexity is O(V), demonstrating awareness of scalability for large course catalogs typical in enterprise environments.

Key Points to Cover

  • Explicitly defining the problem as a Directed Acyclic Graph (DAG) validation
  • Selecting between BFS (Kahn's) and DFS based on specific constraints
  • Correctly implementing in-degree tracking or recursion stack management
  • Identifying that a cycle indicates an unsolvable schedule scenario
  • Articulating O(V + E) time complexity for optimal performance

Sample Answer

To solve the Course Schedule problem, I would first treat each course as a node and each prerequisite pair as a directed edge from the required course to the dependent course. The core challenge is detecting if a cycle e…

Common Mistakes to Avoid

  • Failing to handle disconnected components where multiple independent subgraphs exist
  • Confusing undirected cycle detection with directed cycle detection logic
  • Using an adjacency matrix instead of a list, leading to unnecessary O(V^2) space
  • Ignoring the case where the input array is empty or contains single nodes

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 145 Algorithms questionsBrowse all 24 Oracle questions