Smallest Build Order
MediumGraphs ยท LinkedIn
A build has n modules numbered 0 to n - 1. Each [u, v] in edges means module u must be built before module v.
Return the build order that is lexicographically smallest among all valid orders, as a list of all n modules. If no valid order exists, return an empty list.
Example 1
- Input:
- n = 5, edges = [[3, 1], [4, 1], [2, 0]]
- Output:
- [2, 0, 3, 4, 1]
- Explanation
- Modules 2, 3 and 4 can start; taking 2 first unlocks 0, which is smaller than the others, so 0 comes next.
Example 2
- Input:
- n = 3, edges = [[0, 1], [1, 2], [2, 1]]
- Output:
- []
Example 3
- Input:
- n = 4, edges = [[1, 0], [1, 0], [3, 2]]
- Output:
- [1, 0, 3, 2]
- Explanation
- Repeated edges are allowed and mean the same thing as one copy.
Constraints
1 <= n <= 10^50 <= edges.length <= 2 * 10^50 <= u, v < n; edges may repeat andumay equalv