Pattern

Topological sort

Order items with pairwise "this must come before that" constraints, and detect when no valid order exists.

What it is

Topological sort produces a linear ordering of the nodes of a directed graph such that every edge points from an earlier node to a later one — a valid answer to "what order can these dependent things happen in." It only exists when the graph has no cycle, so the algorithm and the cycle check are the same piece of work: repeatedly take a node with no remaining unsatisfied dependency (in-degree zero), output it, and remove its outgoing edges, which may free up new nodes to take next (Kahn's algorithm); if you run out of removable nodes before every node is output, a cycle exists and no ordering is possible.

When it applies

Tells in the problem

The classic mistake

Building the ordering (usually via DFS with a visited set) but forgetting to distinguish "currently being visited on this recursion path" from "already fully processed" is the error interviewers report most — without that distinction, a back edge to a node that's still mid-recursion looks identical to a normal cross edge to an already-finished node, so a genuine cycle slips through undetected. This happens because a single "visited" boolean is enough to avoid infinite recursion, so it's easy to stop there and think cycle detection is already handled. Catch it by using two states (in-progress, done) instead of one, or by using Kahn's algorithm instead, where the cycle check falls out for free as "fewer nodes were output than exist."

Questions to start with

All 4 topological sort questions

Problem statement, examples and hints are free on every page; the worked approach, solution and tests are in the company guides.

Free starter pack

13 must-tier questions with full solutions

Sign in with an email — no purchase — and read them in the full reader.

No password, no spam. One sign-in email; you can read the pack in the full reader.