Skip to the solution
MediumDSA12 min read

Course Schedule: detect cycle with topological sort (Kahn vs DFS)?

236 views

The problem

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 with collections.deque is 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.

  • topo
  • graph
  • Amazon

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read ยท 9 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonKahn and DFS side by side: orders, stuck sets and the actual cycle
PythonA 200,000-node chain: Kahn and explicit-stack DFS, no recursion

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 111 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

Word Ladder: shortest transformation via BFS โ€” how do you build the wildcard graph?

Continue