Module build order
A monorepo has modules that depend on other modules. Find a build order or detect a cycle – topological sorting with Kahn's algorithm.
A monorepo build tool (like Nx, Bazel or Gradle) has to build every module after the modules it depends on. Modules are numbered 0 … n-1 and a pair [a, b] means "a depends on b", i.e. b has to be built before a.
Task
Return a list of all n modules in an order in which they can be built (every module exactly once, every dependency built earlier). If there is no such order (the dependencies form a cycle, including [a, a]), return an empty list.
There are often many valid orders – the tests accept any of them.
Signatures: buildOrder(n, dependencies) (JS/TS), build_order(n, dependencies) (Python), Solution.BuildOrder (C#, int[][]), Solution.buildOrder (Java, int[][]), BuildOrder (Go, [][]int).
Examples
n | dependencies | Sample result |
|---|---|---|
3 | [[1, 0], [2, 1]] | [0, 1, 2] – the only option |
4 | [[1, 0], [2, 0], [3, 1], [3, 2]] | [0, 1, 2, 3] or [0, 2, 1, 3] |
3 | [] | any permutation, e.g. [0, 1, 2] |
2 | [[0, 1], [1, 0]] | [] – a cycle |
Constraints
1 ≤ n ≤ 100,000, up to 200,000 dependencies, possibly repeated.- A dependency chain can be 100,000 long – a recursive DFS overflows the stack.
Expected complexity
O(V + E) time, O(V + E) memory.