Topological Sort
A directed graph arrives as an object: each key is a node and its value lists the nodes its outgoing edges point to. Every node appears as a key, even one with no edges. Return a topological order: every edge goes from an earlier node to a later one. When several orders exist, return the lexicographically smallest, comparing node names as strings. Return [] when the graph has a cycle, since then no order exists.
topologicalSort({ a: ["b", "c"], b: ["d"], c: ["d"], d: [] }) -> ["a", "b", "c", "d"]
topologicalSort({ b: ["a"], a: [], c: [] }) -> ["b", "a", "c"] // "a" waits for "b"; "c" is free but sorts after "a"
topologicalSort({ a: ["b"], b: ["a"] }) -> []Hints
Hint 1
Count in-degrees from the adjacency lists; the nodes with none are ready. Pop a ready node, append it, and lower the in-degree of each neighbour, releasing the ones that reach zero.
Hint 2
A plain queue gives some valid order; a min-heap, or a sorted insertion, over the ready nodes gives the lexicographically smallest one.
Hint 3
If the result holds fewer nodes than the graph has keys, the rest sit on or behind a cycle: return []. Count the nodes from the keys, not from the edges.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.