Payments app~30 min2s · 256 MBtarget O((n + m) log n) time, O(n + m) spaceclassic twin: lc-210topological-sort
A payment processor closes its books each night with n settlement steps, numbered from 0. Some steps need other steps to finish first. One step, the target, produces the report that the regulator waits for.
The operators want the report out as early as possible. So they run the steps that the report needs first, in any valid order, then the report itself, and only then everything else.
Write settlement_order(n, deps, target).
deps[i] is [a, b]: step a must run before step b. A pair may appear twice.Input: n = 8, deps = [[5,2],[2,6],[6,3],[0,7],[1,7],[4,3]], target = 3
Output: [4, 5, 2, 6, 3, 0, 1, 7]Step 3 needs 6 and 4, step 6 needs 2, and step 2 needs 5. So the critical steps are 3, 6, 4, 2 and 5. Steps 0, 1 and 7 are not critical. A heap holds the ready steps, critical steps first.
| Step run | Ready critical steps | Ready other steps | Why this one |
|---|---|---|---|
| 4 | 4, 5 | 0, 1 | critical, smaller than 5 |
| 5 | 5 | 0, 1 | critical |
| 2 | 2 | 0, 1 | freed by 5 |
| 6 | 6 | 0, 1 | freed by 2 |
| 3 | 3 | 0, 1 | freed by 6 and 4: the report |
| 0 | 0, 1 | smaller of the others | |
| 1 | 1 | next | |
| 7 | 7 | freed by 0 and 1 |
A plain smallest-first order would start with 0 and 1 and delay the report.
Input: n = 3, deps = [[0,1],[1,2],[2,1]], target = 0
Output: []Steps 1 and 2 wait for each other. The report does not need them, but no order of all steps exists.
Input: n = 1, deps = [], target = 0
Output: [0]One step, which is the target.
1 ≤ n ≤ 100,000, and 0 ≤ target < n0 ≤ deps.length ≤ 200,000, and each rule joins two steps from 0 to n - 1Scanning all steps and rules for the best ready step, once for each of the n steps, costs about n × (n + m) = 3 × 10^10 steps. Marking the critical steps once, then using a heap of ready steps, costs O((n + m) log n), about 5 × 10^6 steps.