Topological Order

Topological Order

Given a directed acyclic graph, return a valid topological ordering: every node appears before all nodes it points to. To make the answer unique, when several nodes are ready (in-degree 0), pick the lexicographically smallest first.

topologicalOrder(graph)

Input format: directed edges as a,b pairs (a → b). Output the ordering space-separated.

Examples

a,b a,c b,d c,d     // → a b c d
x,y                 // → x y

Walkthrough

What a topological order actually requires

For every edge A → B, A must appear before B in the output. Edges represent dependencies, and you're lining up nodes so no dependency is violated. Only possible without a directed cycle — a cycle would force some node before and after another, a contradiction. Since the graph is guaranteed a DAG, an ordering always exists; the task is constructing the lexicographically smallest one.

Why in-degree is the key signal

A node can be placed the moment none of its prerequisites remain unplaced — every edge pointing into it already "used up." Track this as in-degree: edges still pointing in, unsatisfied. In-degree 0 means no outstanding prerequisites — safe to output now. Kahn's algorithm: repeatedly remove in-degree-0 nodes; removing a node lowers its neighbors' in-degree, possibly unlocking new zero-in-degree nodes.

Building the approach

  1. Compute every node's in-degree.
  2. Collect all in-degree-0 nodes into a ready pool.
  3. Repeatedly take a node from the pool (smallest name first, for a unique answer), append it to the output, decrement each neighbor's in-degree. Any neighbor hitting 0 joins the pool.
  4. Continue until the pool is empty. Every node in the output means a valid order; incompleteness would only happen with a cycle, ruled out here.

Why this guarantees correctness

A node is only placed after all its prerequisites, since it doesn't join the ready pool until its in-degree hits zero, which only happens after every node with an edge into it has already been output. This enforces the topological property globally, not just locally. Always picking the smallest ready node pins down one specific, deterministic ordering.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.