Music streaming app~30 min2s · 256 MBtarget O(n + m) time, O(n + m) spacetopological-sort
A streaming service prepares each new release from many processing modules, such as encoding, subtitles and artwork. Each module takes a known number of minutes to build, and it can start only when every module it depends on has finished. The farm has as many machines as it needs, so modules without a dependency between them build at the same time.
The team wants to know the earliest minute at which the whole release is ready. A circular dependency makes that impossible.
Write earliest_finish(n, durations, before, after).
0 to n - 1. Module m takes durations[m] minutes.j of before and after says that module after[j] can start only when module before[j] has finished. A pair may repeat.-1.Input: n = 6, durations = [3, 2, 4, 1, 5, 2], before = [0, 0, 1, 2, 3, 2], after = [1, 2, 3, 3, 4, 5]
Output: 13The trace takes modules in an order where all prerequisites come first.
| Order | Module | Minutes | Starts at | Finishes at |
|---|---|---|---|---|
| 1 | 0 | 3 | 0 | 3 |
| 2 | 1 | 2 | 3 | 5 |
| 3 | 2 | 4 | 3 | 7 |
| 4 | 3 | 1 | 7 | 8 |
| 5 | 5 | 2 | 7 | 9 |
| 6 | 4 | 5 | 8 | 13 |
Module 3 waits for modules 1 and 2. Module 2 finishes at minute 7, later than module 1 at 5, so module 3 starts at 7. Module 4 finishes last, at minute 13, so the output is 13.
Input: n = 3, durations = [1, 1, 1], before = [0, 1, 2], after = [1, 2, 0]
Output: -1Module 0 waits for module 2, module 1 waits for module 0, and module 2 waits for module 1. Nothing can start, so the output is -1.
Input: n = 3, durations = [4, 9, 2], before = [2], after = [0]
Output: 9Module 2 builds first, from minute 0 to 2, and then module 0, from minute 2 to 6. Module 1 has no prerequisite and finishes at minute 9, the latest. The output is 9.
1 ≤ n ≤ 100,000 (modules); durations has n entries, each between 1 and 10,000 (minutes)1 ≤ before.length ≤ 100,000; after has the same length0 ≤ before[j], after[j] < nRepeating "update every dependency" until nothing changes needs up to n passes over m dependencies, about 10^10 steps. Processing a module only after all its prerequisites are done needs one step for each module and each dependency. The longest total is 10^5 × 10^4 = 10^9 minutes, which fits in a 32-bit integer.