Problem · Graph
Lexicographically Smallest Dependency Order
Learn this problemProblem statement
There are n tasks labeled from 0 to n - 1. Each pair [before, after] in dependencies means that before must be completed before after.
Return the lexicographically smallest order that completes every task. If the dependencies contain a cycle, return an empty array.
Function
dependencyOrder(n: int, dependencies: int[][]) → int[]Examples
Example 1
n = 4dependencies = [[0,2],[1,2],[1,3]]return = [0,1,2,3]Tasks 0 and 1 begin ready, so task 0 is chosen first; the remaining choices follow the same smallest-label rule.
Example 2
n = 3dependencies = [[0,1],[1,2],[2,0]]return = []Every task belongs to a cycle, so no complete order exists.
Constraints
1 <= n <= 1000000 <= dependencies.length <= 200000- Every dependency contains two distinct valid task labels.
- No dependency pair is repeated.