Tasks have prerequisite tasks and form a directed acyclic graph. Return a valid execution order in which each task appears after all its prerequisites.
For this exercise, task IDs are integers and ties are resolved by returning the lexicographically smallest valid order. The task-ID representation and tie rule make the dependency-ordering follow-up deterministic.
Function Signature
order_tasks(n: int, dependencies: list[list[int]]) -> list[int]
Input
Tasks are numbered from 0 through n - 1. Each pair [task, prerequisite] means prerequisite must occur before task.
Output
Return all task IDs exactly once in the lexicographically smallest valid order. Lexicographic comparison uses integer values at the first differing position. Return an empty list when n is zero.
Constraints
-
0 <= n <= 100000
.
-
0 <= len(dependencies) <= 200000
.
-
Every referenced task ID is in
[0, n)
.
-
There are no repeated dependency pairs or self-dependencies.
-
The graph is guaranteed to be acyclic.
Examples
Input: n = 4, dependencies = [[2,0],[2,1],[3,1]]
Output: [0,1,2,3]
Input: n = 4, dependencies = [[0,2],[1,2]]
Output: [2,0,1,3]
Input: n = 3, dependencies = []
Output: [0,1,2]
Input: n = 0, dependencies = []
Output: []