Build Packages as Dependencies Are Discovered
Problem statement
A build system learns package dependencies over a sequence of iterations. Package IDs range from 0 through packageCount - 1. Initially, no package is declared or built.
batches[t] contains the complete declarations arriving in iteration t. A declaration [p, d1, d2, ...] names package p and all of its dependencies. The row [p] declares a package with no dependencies.
- Add every declaration in the current batch before building.
- A declared package builds once all of its dependencies have built. Building is immediate, so keep unlocking packages in the same iteration until no more can build.
- A dependency without a declaration is unavailable. Cycles and packages waiting on them remain pending.
- Each package builds at most once over the whole input.
Return one row per iteration containing the newly built package IDs in ascending order. Return an empty row when that iteration builds nothing. The row reports a set of completed packages, not their execution order.
Function
buildReadyPackages(packageCount: int, batches: int[][][]) → int[][]Examples
Example 1
packageCount = 4batches = [[[2,1],[1,0]],[[0]],[[3,2]]]return = [[],[0,1,2],[3]]Iteration 0 declares 2 waiting on 1, and 1 waiting on undeclared 0, so its row is empty. Iteration 1 declares dependency-free 0, which builds, then unlocks 1 and 2. Its row is [0,1,2]. Iteration 2 declares 3 waiting on already-built 2, giving [3]. Return [[],[0,1,2],[3]].
Example 2
packageCount = 4batches = [[[2],[1,0],[0,1]],[[3,2]],[]]return = [[2],[3],[]]Packages 0 and 1 wait on each other and remain pending. Package 2 has no dependencies and builds in iteration 0. Package 3 depends on 2 and builds when declared in iteration 1. The final empty iteration builds nothing. Return [[2],[3],[]].
Constraints
1 <= packageCount <= 200.1 <= batches.length <= 200. Each batch contains0to200declarations.- Each declaration contains
1to201entries. - Every package or dependency ID is an integer in
[0, packageCount - 1], so it is at most199. - Each package is declared at most once across all batches. Dependency IDs within a declaration are distinct.
- The total number of dependency entries is at most
2000. Self-dependencies and cycles are allowed.