Music streaming app~25 min2s · 256 MBtarget O((n + m) log n) time, O(n + m) spacetopological-sort · heaps
A streaming app builds a "watch next" queue for a series. Some episodes only make sense after others: a rule says that episode a must be watched before episode b. The queue must respect every rule.
Many orders may satisfy the rules, and the app wants one predictable choice: whenever several episodes are ready to watch, it picks the one with the lowest number. If the rules contradict each other, the app shows no queue at all.
Write viewing_order(n, requires).
0 to n - 1.[a, b] in requires means episode a must come before episode b. Pairs may repeat.n episodes. If the rules contain a cycle, so that some episode never becomes ready, return an empty list.Input: n = 6, requires = [[2, 0], [2, 3], [0, 4], [3, 4], [1, 4], [5, 1]]
Output: [2, 0, 3, 5, 1, 4]The trace keeps the number of unmet rules for each episode, and the set of ready episodes.
| Step | Ready episodes | Watch | Unlocked afterwards |
|---|---|---|---|
| 1 | 2, 5 | 2 | 0 and 3 |
| 2 | 0, 3, 5 | 0 | none (episode 4 still waits for 3 and 1) |
| 3 | 3, 5 | 3 | none (episode 4 still waits for 1) |
| 4 | 5 | 5 | 1 |
| 5 | 1 | 1 | 4 |
| 6 | 4 | 4 | none |
The output is [2, 0, 3, 5, 1, 4]. Watching in first-come order would give [2, 5, 0, 3, 1, 4], which is also valid, but it is not the lowest-numbered choice at step 2.
Input: n = 3, requires = [[0, 1], [1, 2], [2, 0]]
Output: []Episode 0 needs 2, episode 2 needs 1, and episode 1 needs 0, so none can start.
Input: n = 3, requires = []
Output: [0, 1, 2]With no rules, every episode is always ready, and the lowest number goes first.
1 ≤ n ≤ 100,000 (episodes)0 ≤ requires.length ≤ 100,000 (rules); each rule has 2 numbers from 0 to n - 1Scanning all episodes and all rules for every step costs about n × (n + m), about 2 × 10^10 steps. You need to keep, for each episode, how many unmet rules it has, and to find the lowest ready episode without scanning. A heap of ready episodes gives it in log n.