Parcel-delivery app~30 min2s · 256 MBtarget O(n + m) time, O(n + m) spaceclassic twin: lc-1136topological-sort
A freight depot prepares each shipment in steps, such as picking, packing, labelling and loading. A step takes a fixed number of minutes and starts the moment every step it needs has finished. The depot has enough workers to run any number of steps at once.
The team wants two numbers: the minutes until the shipment is ready, and how many steps have no slack. A step has no slack when delaying it by a minute delays the shipment by a minute. If the needs loop, the shipment can never be ready.
Write critical_steps(minutes, needs).
minutes[i] is how long step i takes. The steps are numbered from 0 to len(minutes) - 1.needs[j] = [step, required] means step cannot start until required has finished. A pair may repeat.[total, critical]: the minutes until every step has finished, and the number of steps that have no slack.[-1, -1] when the needs contain a loop.Input: minutes = [3, 2, 4, 1, 2, 2], needs = [[2, 0], [2, 1], [3, 2], [4, 2], [5, 3], [5, 4]]
Output: [11, 4]The solution runs two passes. The forward pass gives each step its earliest start. The backward pass gives each step its latest start without delaying the shipment. The difference is the slack.
| Step | Minutes | Earliest start | Latest start | Slack |
|---|---|---|---|---|
| 0 | 3 | 0 | 0 | 0 |
| 1 | 2 | 0 | 1 | 1 |
| 2 | 4 | 3 | 3 | 0 |
| 3 | 1 | 7 | 8 | 1 |
| 4 | 2 | 7 | 7 | 0 |
| 5 | 2 | 9 | 9 | 0 |
The shipment takes 11 minutes. Steps 0, 2, 4 and 5 have no slack, and step 1 has 1 minute of slack.
Input: minutes = [1, 1], needs = [[0, 1], [1, 0]]
Output: [-1, -1]Step 0 waits for step 1 and step 1 waits for step 0, so neither can start.
Input: minutes = [4, 7, 2], needs = []
Output: [7, 1]With no needs, all three steps run at once. The shipment takes 7 minutes, and only the 7-minute step has no slack.
1 ≤ len(minutes) ≤ 20,000, and 1 ≤ minutes[i] ≤ 1,0000 ≤ len(needs) ≤ 40,000, and both numbers of a pair are valid step numbersA longest chain of steps can have 20,000 steps, so repeating a sweep over all needs once for each step takes about 800,000,000 steps. Two passes along a topological order handle each need a couple of times, which is about 120,000 steps.