← All Exercises
Build Order via Topological Sort
intermediatejavascript
Background
Build systems, package managers, and migration runners all need dependency order. Taking the smallest ready node first makes the output deterministic and testable.
Problem
Given build nodes and dependency edges where [a, b] means a must build before b, produce the lexicographically smallest valid build order using Kahn’s algorithm with a sorted ready list. If a cycle prevents completion, report valid false. Output the order and validity flag.
Input
A JSON object {"nodes": string[], "edges": [string, string][]} forming dependencies with no duplicates.Output
A JSON object {"order": string[], "valid": boolean} where valid is true exactly when all nodes are ordered.Sample tests
Sample 1
Input: {"nodes":["app","cli","core","db","ui"],"edges":[["core","app"],["db","core"],["ui","cli"],["core","cli"]]}Expected: {"order":["db","core","app","ui","cli"],"valid":true}Sample 2
Input: {"nodes":["a","b","c"],"edges":[["a","b"],["b","c"],["c","a"]]}Expected: {"order":[],"valid":false}Your solution
Learning objective
Implement Kahn’s algorithm with a deterministic frontier and cycle detection.