← Microsoft Interview Insights

Microsoft·Software Engineer·Technical Phone Screen·Intermediate

Intermediate
Apr 2026

Summary

Microsoft SWE interview with a graph/topological sort problem. Pretty standard stuff for this kind of role but the cycle detection piece is where things get interesting.

Questions Asked (1)

Q1

Given a number of courses and a list of prerequisite pairs, return a valid order to complete all courses. If no valid ordering exists due to a cycle, return an empty array.

Algorithms & Data Structures
Author's notes

Topological sort, which I knew going in, but I fumbled the cycle detection part longer than I should have.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Model the courses and prerequisites as a directed graph, then perform a topological sort using either Kahn's algorithm (BFS with in-degree tracking) or DFS with cycle detection. If the topological sort produces an ordering containing all courses, return it; otherwise, return an empty array to indicate a cycle.

Pro tip: Explicitly discuss trade-offs between Kahn's algorithm and DFS: Kahn's is iterative and naturally detects cycles via leftover nodes, while DFS uses recursion and detects cycles via back edges. Mentioning both shows depth and helps you choose the right tool for the constraints.

1. Clarify and Model the Problem

Confirm input format (number of courses, prerequisite pairs) and edge cases (empty input, self-prerequisites). Model courses as nodes and prerequisites as directed edges from prerequisite to dependent course.

2. Choose an Algorithm

Select either Kahn's algorithm (BFS with in-degree) or DFS with cycle detection. Explain why one might be preferred based on constraints like recursion depth or need for early cycle detection.

3. Implement the Topological Sort

For Kahn's: compute in-degrees, use a queue to process nodes with zero in-degree, and build the order. For DFS: perform depth-first search, track visited and recursion stack, and append nodes in post-order.

4. Detect Cycles and Validate

After the sort, check if the result contains all courses. If not, a cycle exists, so return an empty array. For DFS, detect cycles via back edges during traversal.

5. Analyze Complexity and Test

State time and space complexity (O(V+E) for both). Walk through a simple example and a cycle case to verify correctness.

Key Points to Mention

  • Graph representation: adjacency list for efficiency
  • Topological sort algorithms: Kahn's (BFS) and DFS-based
  • Cycle detection: in-degree count vs. recursion stack
  • Time and space complexity: O(V+E) time, O(V+E) space
  • Handling edge cases: no prerequisites, disconnected components, self-loops
  • Returning empty array when cycle detected

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.