Skip to the code
cf.
+25 XP

#440 Bundle Build Order

medium

A build tool must order n modules numbered 0 to n - 1. Each deps[i] = [a, b] means module a depends on module b, so b must come before a.

Write buildOrder(n, deps) that returns the build order as an array of module numbers. To make the order unique, whenever several modules are ready (everything they depend on is already built), build the smallest-numbered one first. If the dependencies contain a circle, return [].

Example 1

Input: n = 4, deps = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3]

Module 0 goes first. Then 1 and 2 are both ready, and 1 is smaller. Module 3 needs both.

Example 2

Input: n = 4, deps = [[0,3],[1,3],[2,0]]
Output: [3,0,1,2]

Only 3 is ready at first. It frees 0 and 1; 0 is smaller. Then 1 and 2 are ready, and 1 is smaller.

Constraints

  • 1 <= n <= 10000
  • 0 <= deps.length <= 50000
  • 0 <= a, b < n
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).