Question presented to candidate: "Given a directed graph with n nodes and a list of edges, tell me whether it contains a cycle. If you can, return one cycle as a list of nodes. Please code it in Python."
What a strong answer should cover:
- Why a single "visited" flag gives false positives in a directed graph (a diamond is not a cycle).
- Three-colour DFS: WHITE/GRAY/BLACK, a cycle exactly when an edge reaches a GRAY node (a back edge), and why BLACK nodes are safe.
- Restarting DFS from every unvisited node, self-loops, and recovering the cycle from the current path.
- O(V + E) time and O(V) extra space, with Kahn's algorithm as the non-recursive alternative.
- Python specifics: a nested
visitfunction closing over acolorlist,any(...)over start nodes, the 1000-frame default recursion limit, and returning the cycle with list slicing.
Clarifying questions expected:
- "Do you need just true/false, or the cycle itself?"
- "Can there be self-loops, and is the graph connected?"
Code / implementation expected: Yes โ a three-colour DFS hasCycle (ideally returning the cycle) in Python.