Task label order
HardOnline Assessment
Order the jobs of a repair crew so that the most urgent jobs finish as early as possible.
There are n jobs numbered 1 to n, and a lower number means a more urgent job. The crew does one job at a time. Each pair [a, b] in needs means that job a must be completed before job b starts. Pairs can repeat, and a pair like [3, 3] can never be satisfied.
Among all valid orders, the crew's boss wants this one: job 1 is done as early as possible; among the orders that achieve that, job 2 is done as early as possible; among those, job 3 as early as possible, and so on. (Putting the smallest *available* label first at each step does not do this.)
Input: n, the number of jobs, and needs, a list of [a, b] precedence pairs.
Output: that order as a list of the job numbers 1 to n, each exactly once, or an empty list if the precedence pairs cannot all be satisfied. The order is unique, so there are no ties to break.
There can be more than a thousand jobs, and trying all valid orders is hopeless.
Example 1
- Input:
- [3,[[3,1]]]
- Output:
- [3,1,2]
- Explanation
- Job 3 must come before job 1. Putting job 3 first lets job 1 start at position 2, the earliest it can ever be, and job 2 fills the last slot. Doing the jobs in plain label order (2 before 3) would delay job 1, so the answer is [3, 1, 2].
Example 2
- Input:
- [6,[[6,3],[3,1],[5,2]]]
- Output:
- [6,3,1,5,2,4]
- Explanation
- Job 1 needs 3, which needs 6, so job 1 cannot be earlier than the third slot: 6, 3, 1. Next, job 2 needs 5, so it goes at the earliest remaining chance: 5, 2. Job 4 has no urgency and goes last: [6, 3, 1, 5, 2, 4]. Starting with the smallest available label (job 4) would push job 1 back.
Example 3
- Input:
- [5,[[4,5],[2,3],[3,2]]]
- Output:
- []
- Explanation
- Jobs 2 and 3 each have to come before the other, which is impossible, so there is no valid order and the answer is the empty list.
Constraints
1 <= n <= 1,2000 <= needs.length <= 1,500- every pair
[a, b]inneedshas1 <= a, b <= n; pairs can repeat andacan equalb