Pipeline Execution Order

HardData EngineeringGraphArraySorting

Description

Given n pipeline tasks labeled 0..n-1 and a list of dependency edges [a, b] meaning task a must run before task b, return a valid execution order (a topological sort). When several tasks are ready, always choose the one with the smallest id. If the dependencies contain a cycle, return an empty array.

Examples

Input:4, [[0,1],[0,2],[1,3],[2,3]]
Output:[0,1,2,3]
Explanation:

Tasks with no remaining prerequisites run first, always taking the smallest available id, until every task is placed or a cycle blocks all progress.

Input:3, []
Output:[0,1,2]
Explanation:

Tasks with no remaining prerequisites run first, always taking the smallest available id, until every task is placed or a cycle blocks all progress.

Input:2, [[1,0]]
Output:[1,0]
Explanation:

Tasks with no remaining prerequisites run first, always taking the smallest available id, until every task is placed or a cycle blocks all progress.

Constraints

  • 1 ≤ n ≤ 10⁴
  • 0 ≤ edges ≤ 10⁵

Ready to solve this problem?

Practice solo and sharpen your skills for technical interviews.