← Microsoft Interview Insights
I went with Kahn's algorithm because tracking in-degrees felt cleaner to explain out loud.
Start by clarifying the problem constraints and then present Kahn's algorithm (in-degree queue) as the primary solution, explaining how it naturally detects cycles and handles disconnected components. Alternatively, describe the DFS post-order approach with cycle detection using recursion stack, and compare trade-offs. Walk through a small example to illustrate.
Pro tip: Mention that Kahn's algorithm can be easily modified to return the lexicographically smallest topological order using a min-heap, which is a common follow-up at Microsoft. Also, note that if the graph has multiple connected components, both approaches handle them seamlessly by initializing the queue with all in-degree zero vertices or iterating over all vertices in DFS.
Ask about input size, whether the graph is guaranteed to be a DAG, and if any specific ordering (e.g., lexicographical) is required. Confirm the expected output format.
Select either Kahn's algorithm (BFS with in-degree queue) or DFS post-order. Explain the steps: compute in-degrees, use a queue for Kahn's, or use DFS with visited and recursion stack for cycle detection.
For Kahn's, initialize the queue with all vertices having in-degree zero; if the queue empties before processing all vertices, a cycle exists. For DFS, iterate over all unvisited vertices and use a recursion stack to detect back edges.
Write clean code with appropriate data structures (e.g., adjacency list, queue, arrays for in-degree/visited). Ensure edge cases like empty graph or single vertex are handled.
State time and space complexity (O(V+E) for both). Walk through a small example, including a graph with a cycle and one with disconnected components, to verify correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.