Lexicographically smallest topological sort

Write codeMedium25 min

Your task

Given a directed graph with n nodes (0..n-1) and edges [u, v] meaning u must come before v, return the lexicographically smallest topological ordering as a list of node labels. If the graph has a cycle (no valid ordering), return an empty list. Constraints: 1 <= n <= 2000.

Examples

lexicographic_topo_sort(n: int, edges: list[list[int]]) -> list[int]
Example 1
Inputlexicographic_topo_sort(3, [[0, 2], [1, 2]])
Output[0, 1, 2]