Monitoring~30 min2s · 256 MBtarget O(total length of runs) time, O(n + total length) spaceclassic twin: lc-444topological-sort
A pipeline runs n stages in one fixed order, but the order is not documented. Each trace records some of the stages in the order they ran, and may skip stages. All traces come from the same real order, so they never contradict each other.
The team reads the traces one by one. They want to know after how many traces the stage order becomes certain, meaning only one order of all n stages fits the traces read so far.
Write runs_to_pin_down(n, runs).
0 to n - 1. runs[i] lists some of the stages in the order they ran in trace i. The traces never contradict each other.n stages fits the first r traces when every stage comes before the stages that follow it in each of those traces.r such that exactly one order fits the first r traces.-1 when more than one order fits even after all the traces.Input: n = 5, runs = [[1, 2], [3, 4], [0, 1], [2, 3]]
Output: 4Each pair of neighbours in a trace is a rule. The order is certain when exactly one stage is ready at every step. The table counts the orders that fit after each trace, found by trying all 120 orders.
| Runs read | Rules known | Orders left |
|---|---|---|
| 0 | none | 120 |
| 1 | 1 before 2 | 60 |
| 2 | 1 before 2, 3 before 4 | 30 |
| 3 | 0 before 1, 1 before 2, 3 before 4 | 10 |
| 4 | 0 before 1, 1 before 2, 2 before 3, 3 before 4 | 1 |
After the 4th trace one order remains, so the answer is 4. Reading the traces one at a time, the last needed rule arrives in the 4th.
Input: n = 3, runs = [[0, 1, 2]]
Output: 1One trace that lists every stage fixes the order, so 1 trace is enough.
Input: n = 3, runs = [[0, 1]]
Output: -1Stage 2 is not in any trace, so it can go anywhere. Several orders fit.
1 ≤ n ≤ 5,000, and 0 ≤ len(runs) ≤ 20,0001 ≤ len(runs[i]) ≤ 5,000, every stage number is below n, and a trace lists no stage twiceRe-checking every prefix of the traces from scratch costs about 20,000 checks, each over all the rules, which is far too slow. But each trace only adds rules, and the order is unique only if its consecutive stages are joined by rules. One pass over the traces is enough.