AniUI Academy
hard+350 XPPractice

Order a dependency list

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.

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.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.