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.
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 cleanlytopologicalSort({ app: ["lodash"] });
// ["lodash", "app"] — a dependency that's not a key is still includedWhat 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.
- 1.orders a simple chain
- 2.orders a diamond of dependencies
- 3.follows the specified walk order
- 4.includes dependencies that are not themselves keys
- 5.handles independent tasks and an empty graph
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.