Engineering platform~25 min2s · 256 MBtarget O((n + m) log n) time, O(n + m) spacetopological-sort
A build system for a software platform keeps a graph of build targets, numbered from 0. A target depends on other targets and can be built only after they are built.
A developer changes some targets. Each changed target must be rebuilt, and so must every target that depends on a changed one, directly or through others. All other targets keep their old build and are skipped.
Write rebuild_order(n, deps, changed).
n targets, numbered from 0 to n - 1.deps[i] is [a, b]: target b depends on target a, so a is built before b. The same line may appear twice.changed lists the changed targets. A target may be listed twice.Input: n = 8, deps = [[0,2],[1,2],[2,4],[3,4],[4,6],[5,6],[2,7]], changed = [2]
Output: [2, 4, 6, 7]Target 2 changed. Targets 4 and 7 depend on it, and target 6 depends on 4. Targets 0, 1, 3 and 5 are not affected, so they are skipped.
Each affected target counts only the affected targets it waits for. The ready targets sit in a min-heap.
| Step | Ready heap | Built | Order so far |
|---|---|---|---|
| 1 | 2 | 2 | 2 |
| 2 | 4, 7 | 4 | 2, 4 |
| 3 | 6, 7 | 6 | 2, 4, 6 |
| 4 | 7 | 7 | 2, 4, 6, 7 |
Target 2 waits for targets 0 and 1, but they are not rebuilt, so it starts with nothing to wait for.
Input: n = 5, deps = [[3,1],[1,0],[0,4],[2,4]], changed = [2, 3]
Output: [2, 3, 1, 0, 4]Targets 2 and 3 changed. Together they affect every target. Target 4 waits for both 0 and 2, so it comes last.
Input: n = 4, deps = [[0,1],[1,2]], changed = [3]
Output: [3]Target 3 changed, and nothing depends on it. Only target 3 is rebuilt.
1 ≤ n ≤ 50,0000 ≤ deps.length ≤ 100,000, and each dependency is [a, b] with 0 ≤ a, b < n1 ≤ changed.length ≤ nScanning for the next ready target on every step costs about n × (n + m) work, and for n = 50,000 and m = 100,000 that is about 7.5 × 10^9 steps. A heap of ready targets makes each step O(log n), so the whole run costs O((n + m) log n), about 2 × 10^6 steps.