Skip to the solution
MediumDSA13 min read

What is topological sort and when is it used?

1.2k views

The problem

Question presented to candidate: "What is a topological sort, and when would you use one? Walk me through an algorithm for it and code it in Python."

What a strong answer should cover:

  • A topological order lists every node so that each edge u -> v has u before v; it exists only for a DAG (no cycles), and it is usually not unique.
  • Kahn's algorithm: in-degrees, a queue of in-degree-0 nodes, decrement neighbours; fewer than n nodes placed means a cycle.
  • The DFS alternative: reverse post-order, with three colours to catch a back edge.
  • O(V + E) time and space for both, and real uses: build order, package installs, spreadsheets, course prerequisites, DP on a DAG.
  • Python specifics: collections.deque for an O(1) popleft (not list.pop(0)), heapq (a min-heap) for the smallest order, the 1000-frame default recursion limit for DFS, and the standard-library graphlib.TopologicalSorter.

Code / implementation expected: Yes โ€” a kahn(n, edges) function in Python that returns an order or signals a cycle.

  • graphs
  • topological-sort

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

13 min read ยท 12 sections

Python code

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

PythonKahn's algorithm on a build graph, then with a cycle
PythonThe queue picks the order: FIFO vs min-heap, and all 13 orders
PythonDFS reverse post-order on the same build graph

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 39 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

What is dynamic programming?

Continue