Pretty classic graph question for a phone screen.
Start by clarifying the problem constraints (directed graph, possible cycles, input format) and then present Kahn's algorithm (BFS-based) as the primary solution, explaining its O(V+E) time complexity. If time permits, mention the DFS-based approach with cycle detection as an alternative, and discuss trade-offs.
Pro tip: Always check for cycles first—if the graph has a cycle, topological sort is impossible. Mentioning this upfront shows you understand edge cases and prevents incorrect assumptions.
Ask about input format (adjacency list/matrix), whether the graph is guaranteed acyclic, and if multiple valid orders are acceptable. Confirm that the output should be a linear ordering of vertices.
Select either Kahn's algorithm (BFS with in-degree tracking) or DFS with post-order reversal. Explain why you prefer one (e.g., Kahn's is intuitive and detects cycles easily).
Describe the steps: compute in-degrees, enqueue nodes with in-degree 0, process queue while decrementing neighbors' in-degrees, and build the order. For DFS, explain visiting states and cycle detection.
State time and space complexity (O(V+E) time, O(V) space). Discuss edge cases: empty graph, single node, disconnected components, and cycles (return error or empty list).
Walk through a small example (e.g., course prerequisites) to demonstrate correctness. If coding, write clean code with meaningful variable names and test it.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.