Course Schedule (Adjacency List & BFS)

Data Structures
Medium
Cisco
32.3K views

Determine if you can finish all courses given an array of prerequisite pairs. Represent the problem as a graph (Adjacency List) and use Topological Sort via BFS (Kahn's algorithm).

Why Interviewers Ask This

Cisco evaluates this question to assess a candidate's ability to model real-world dependency systems as directed graphs. They specifically test proficiency in choosing the right data structure, an adjacency list, and implementing Kahn's algorithm for topological sorting via BFS. This demonstrates logical reasoning regarding cycle detection and handling edge cases in complex scheduling scenarios.

How to Answer This Question

1. Clarify the problem by defining nodes as courses and edges as prerequisites, explicitly stating that a cycle makes completion impossible. 2. Propose building an Adjacency List to represent the graph efficiently, alongside an array to track in-degrees (incoming edges) for each node. 3. Initialize a queue with all courses having zero in-degree, explaining this represents starting points with no dependencies. 4. Iterate through the queue: remove a course, decrement the in-degree of its neighbors, and add any neighbor reaching zero in-degree to the queue. 5. Conclude by comparing the count of processed courses against the total number of courses; if they match, return true, otherwise false due to a cycle. 6. Analyze time complexity as O(V + E) and space complexity as O(V + E), justifying these metrics based on the traversal.

Key Points to Cover

  • Explicitly mention modeling the problem as a Directed Acyclic Graph (DAG)
  • Correctly implement the in-degree tracking mechanism for Kahn's algorithm
  • Demonstrate understanding of why a queue is essential for BFS-based topological sort
  • Explain the logic behind cycle detection using the processed node count
  • Justify the O(V + E) time and space complexity clearly

Sample Answer

To solve the Course Schedule problem, I first visualize the input as a directed graph where courses are nodes and prerequisite pairs define the edges. My goal is to determine if a valid topological ordering exists, which…

Common Mistakes to Avoid

  • Using DFS instead of BFS when the prompt specifically requests Kahn's algorithm or Topological Sort via BFS
  • Failing to handle the case where the graph contains a cycle, leading to incorrect boolean returns
  • Choosing an Adjacency Matrix over an Adjacency List, resulting in unnecessary O(V^2) space complexity
  • Not initializing the queue correctly by missing nodes with zero initial in-degree

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 166 Data Structures questionsBrowse all 27 Cisco questions