Topological Sort Interview Pattern

Topological Sort Interview Pattern

When a problem says “prerequisites,” “build order,” or “tasks with dependencies,” you are usually looking at a directed acyclic graph—and the topological sort interview pattern. The skill is recognizing the pattern quickly, detecting cycles, and implementing either Kahn’s algorithm (BFS/ indegrees) or a DFS-based order without confusing the edge direction.

The 10-second recognition

Cues:

Talk track:

“I’ll model this as a directed graph. If it’s a DAG, a topological order exists. I’ll use Kahn’s algorithm with indegrees so cycle detection is natural: if we can’t process all nodes, there’s a cycle.”

Clarify edge direction first

This is the #1 interview bug. Ask:

“Does an edge u → v mean u is a prerequisite of v (u before v)?”

Draw one tiny example on the board. Wrong direction produces a confidently wrong order.

Kahn’s algorithm (default for interviews)

  1. Build adjacency list and indegree array/map
  2. Push all zero-indegree nodes into a queue
  3. Pop, append to order, decrement neighbors’ indegrees
  4. Push neighbors that hit zero
  5. If order size < n → cycle → impossible
from collections import deque, defaultdict

def topo_kahn(n, edges):
    graph = defaultdict(list)
    indeg = [0] * n
    for u, v in edges:  # u before v
        graph[u].append(v)
        indeg[v] += 1
    q = deque([i for i in range(n) if indeg[i] == 0])
    order = []
    while q:
        u = q.popleft()
        order.append(u)
        for v in graph[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                q.append(v)
    return order if len(order) == n else []  # empty => cycle

Complexity: O(V + E). Say it once.

DFS-based topological sort

Talk track:

“DFS post-order gives a reverse topo if I finish children before I record the node. Gray nodes detect cycles.”

Prefer Kahn in interviews when the prompt emphasizes “is it possible?”—the leftover nodes story is easy to explain.

Pattern variants candidates commonly see

VariantExtra twist
Course scheduleBoolean: can finish all?
Course orderReturn one valid order
Parallel coursesLevels / minimum semesters → Kahn by layers
Alien dictionaryLetters as nodes; inconsistent order → invalid
Build systemSame idea with packages/tasks

For “minimum number of terms,” process Kahn in layers: each wave is one parallel step.

Failure modes

Complexity and follow-ups

Be ready for:

Practice plan

SessionFocus
1Boolean course schedule (cycle detect)
2Return an order with Kahn
3Layered Kahn for parallel steps
4DFS color cycle detection
5Timed classification: topo vs ordinary BFS

Worked mini-example (say it aloud)

Nodes 0..3, edges 0→1, 0→2, 1→3, 2→3:

If an edge 3→0 existed, you would stall with nodes left—report impossible.

Alien dictionary sketch

Characters are nodes; a wrong lexicographic contradiction means a cycle. Build edges from adjacent word pairs, then Kahn. If words violate prefix rules (longer word before shorter prefix), reject before topo.

Talk track:

“I’ll derive letter edges from sorted word pairs, then topo-sort. Cycle or invalid prefix → no ordering.”

Soft practice note

Topo problems punish silent edge-direction mistakes. If you want timed rehearsal of the “model → indegree → Kahn → cycle” talk track, Luna Interview is built for calm structured practice—not for anything that breaks interview rules.

Day-of checklist

When the prompt is dependencies, reach for topological sort on purpose—then prove the graph is a DAG while you build the order.