You are scheduling n flights, labeled from 0 to n - 1. Some flights must be completed before others can depart because of crew rotations, aircraft positioning, or connecting passengers.
You are given a list dependencies where dependencies[i] = [a, b] means flight a must be completed before flight b can depart.
Return an order in which all n flights can be scheduled so that every dependency is respected. If no such order exists because the dependencies form a cycle, return an empty list.
Function Signature
def flight_order(n: int, dependencies: list[list[int]]) -> list[int]:
Rules
-
A flight is ready once every flight it depends on has already been scheduled.
-
Whenever more than one flight is ready, schedule the one with the smallest label next. This makes the expected output unique: it is the lexicographically smallest valid order.
-
If the dependencies contain a cycle (a pair
[a, a]
counts as one), return
[]
.
Constraints
-
1 <= n <= 2000
-
0 <= len(dependencies) <= 5000
-
len(dependencies[i]) == 2
-
0 <= a, b < n
-
All pairs
[a, b]
are unique.
Examples
Input: n = 4, dependencies = [[0,1],[0,2],[1,3],[2,3]]
Output: [0,1,2,3]
Flight 0 has no prerequisites. Once it is done, flights 1 and 2 are both ready and 1 goes first because it has the smaller label. Flight 3 waits for both 1 and 2.
Input: n = 3, dependencies = [[0,1],[1,2],[2,0]]
Output: []
The pairs form the cycle 0 -> 1 -> 2 -> 0, so every flight waits on another one and none can go first.
Input: n = 4, dependencies = [[2,0],[3,1]]
Output: [2,0,3,1]
Flights 2 and 3 are ready at the start, so 2 goes first. That frees flight 0, which is now the smallest ready label (the ready flights are 0 and 3). Flight 3 goes next and frees flight 1, which goes last.