AniUI Academy

Order a dependency list

hardData Structures+350 XPPractice

A bundler decides which module to evaluate first, a migration runner decides which migration to apply first, a design-token pipeline decides which theme layer to compile first. All of them answer the same question: given what depends on what, what order works?

Implement topologicalSort(graph). graph is a plain object whose keys are task names and whose values are arrays of the names that task depends on. Return an array of names in which every task appears after all of its dependencies. A name that appears only inside a dependency array, never as a key, is treated as a task with no dependencies of its own and must still appear in the result. An empty object returns an empty array. You may assume the input has no cycles.

So the answer is deterministic, use this exact walk: go through Object.keys(graph) in order; for each name not yet added, first recurse into its dependencies in array order, then append the name itself.

Arguments

graphRecord<string, string[]>
Keys are task names, values are the names of tasks they depend on.

Returns

string[] — A deterministic order in which every task comes after each of its dependencies.

Examples

topologicalSort({ c: ["b"], b: ["a"], a: [] });
// ["a", "b", "c"]
topologicalSort({ d: ["b", "c"], b: ["a"], c: ["a"], a: [] });
// ["a", "b", "c", "d"] — the diamond flattens cleanly
topologicalSort({ app: ["lodash"] });
// ["lodash", "app"] — a dependency that's not a key is still included

What it has to do

  • Every task appears after all of the tasks it depends on.
  • Names that appear only as dependencies are included in the result.
  • Each name appears exactly once.
  • Follow the specified walk order so the result is deterministic.
  • Return an empty array for an empty graph.

Notes

  • O(V + E) time, where V is the number of tasks and E is the total number of dependency edges.
  • Depth-first post-order gives the ordering for free: mark a name as seen, recurse into its dependencies, then append the name as the recursion comes back up.
  • A real implementation would also detect cycles — a dependency currently on the recursion stack means a loop. This problem assumes acyclic input to keep the focus on the walk.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +350 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.