Question presented to candidate: "For Course Schedule you can detect the cycle with Kahn's algorithm or with DFS. Explain both, tell me how each one spots a cycle, and when you would choose one over the other. Show me both in Python."
What a strong answer should cover:
- Kahn: in-degrees plus a queue; a cycle exists when fewer than V nodes get placed, and the leftover nodes are the cycle plus everything downstream of it.
- DFS: WHITE/GRAY/BLACK colours; an edge into a GRAY node (a back edge) is a cycle, and the GRAY path gives the exact cycle; reverse finish order is the topological order.
- Both are O(V + E) time and O(V + E) space; they usually produce different valid orders.
- Trade-offs: Kahn has no recursion and gives levels and easy lexicographic order; DFS stops at the first cycle and can print it, but needs an explicit stack on deep graphs.
- Python specifics: recursive DFS hits the default 1000-frame recursion limit (
RecursionError), so an explicit stack (a list of[node, index]frames) or Kahn withcollections.dequeis the robust choice.
Code / implementation expected: Yes โ both a Kahn function and a three-colour DFS function in Python, ideally with the DFS able to return the cycle.