Funcia
Lv.3graphheaptopological-sort

Task Order

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
0

There are n tasks 0..n-1; rules[i] = [a, b] means task a must come before task b. Return an order of all tasks that respects every rule. If several exist, return the lexicographically smallest; if none exists, return [].

Examples

nrulesresult
4[[3, 1], [2, 1], [1, 0]][2, 3, 1, 0]
3[[0, 1], [1, 2], [2, 0]][]
3[][0, 1, 2]

Efficiency

This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.

Function signature

solution(n: int, rules: int[][]) → int[]

Constraints

  • 1≤1 \le n ≤100,000\le 100{,}000, 0≤0 \le rules.length ≤200,000\le 200{,}000
  • 0≤a,b<n0 \le a, b < n; rules may repeat, and a == b is a contradiction.

Expected complexity

Time
O((N + M) log N)
Space
O(N + M)

Examples

nrulesExpected
4[[3,1],[2,1],[1,0]][2,3,1,0]
3[[0,1],[1,2],[2,0]][]
3[][0,1,2]

Hint

Hint

Kahn's topological sort with a min-heap instead of a queue: always take the smallest task whose in-degree is 0. If fewer than n tasks come out there is a cycle. Scanning all tasks for the smallest ready one is O(N2)O(N^2) and exceeds the time limit.

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251630 msderived
Kotlin 2.4 (JVM)1400 msestimated
C# 14 (.NET 10)1400 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness4010verdict only
performance604verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.