Music streaming app~30 min2s · 256 MBtarget O(26 (n + m)) time, O(26 n) spaceclassic twin: lc-1857topological-sort · dp
A video platform processes each upload through numbered stages, from 0. A stage runs only after the stages that lead to it have finished. Each stage is run by one worker pool, named by a letter.
Engineers study chains of stages, where each stage leads to the next. They want the chain in which one pool handles the most stages, because that pool is the bottleneck. A stage that waits for itself, directly or through others, makes the plan invalid.
Write most_stages_one_pool(pools, links).
pools[i] is the letter of the pool that runs stage i. The stages are numbered from 0 to len(pools) - 1.links[i] is [a, b]: stage a leads to stage b. A link may repeat.Input: pools = "bbaaaa", links = [[0,3],[0,5],[1,3],[2,5],[3,4],[4,5]]
Output: 3Stages 0 and 1 are run by pool b, and the others by pool a. The chain 1, 3, 4, 5 has three stages of pool a and one of pool b. No chain has four stages of one pool.
The solution processes the stages in order and keeps, for each stage, the most stages of each pool on any chain that ends there. Only pools a and b appear.
| Stage | Pool | Best a | Best b |
|---|---|---|---|
| 0 | b | 0 | 1 |
| 1 | b | 0 | 1 |
| 2 | a | 1 | 0 |
| 3 | a | 1 | 1 |
| 4 | a | 2 | 1 |
| 5 | a | 3 | 1 |
Stage 5 is reached from stages 0, 2 and 4. It keeps the best count of each pool, which gives 2 of pool a from stage 4, and then adds itself. The largest value in the table is 3.
Input: pools = "ab", links = [[0,1],[1,0]]
Output: -1Stage 0 leads to stage 1 and stage 1 leads back to stage 0, so the links contain a loop.
Input: pools = "aabaa", links = []
Output: 1With no links, every chain is one stage, so the answer is 1.
1 ≤ pools.length ≤ 50,000, and pools holds the letters a to z0 ≤ links.length ≤ 100,000, and each link is [a, b] with 0 ≤ a, b < pools.lengthA layered graph with two stages per layer and 25,000 layers has 2^25000 chains, so listing chains is impossible. The count method handles each link once and updates 26 counts for it, so it costs about 26 × 100,000 = 2.6 × 10^6 steps.