Task Order
NetflixOnsiteMedium
TaskGraph(n) manages n tasks labeled 0 to n - 1. add_dependency(before, after) states that task before must finish before task after can start. The same pair can be added more than once, and a task can depend on itself.
Part 1: Smallest valid order
order() returns an order of all n tasks in which every task appears after all of its prerequisites. When several orders exist, it returns the lexicographically smallest one, comparing the lists element by element. When the dependencies contain a cycle, so that no order exists, it returns [].
- Example 1
- init
[5]- operations
[["order",[]],["add_dependency",[3,1]],["add_dependency",[4,1]],["add_dependency",[1,0]],["order",[]],["add_dependency",[2,0]],["order",[]]]- Output
[[0,1,2,3,4],null,null,null,[2,3,4,1,0],null,[2,3,4,1,0]]
Why: With no dependencies the order is
0, 1, 2, 3, 4. After adding3 -> 1,4 -> 1and1 -> 0, tasks2,3and4can go first, and1and0must wait: the smallest valid order is2, 3, 4, 1, 0. Adding2 -> 0changes nothing.
Constraints
1 <= n <= 10^40 <= before, after < n1 <= len(operations) <= 10^4