KatInterview

Schedule Tasks with Precedence Constraints

Trees & GraphsAuto-graded · 23 test cases
HardAuto-gradedTrees & Graphstopological sortgraphbfs

Last updated

Determine a valid sequential execution order for a set of tasks given dependency rules, or detect impossible circular dependencies.

You are organizing a build pipeline consisting of $n$ distinct jobs indexed from $0$ to $n - 1$.

You are given an integer $n$ and an array prerequisites where each element prerequisites[i] = [a, b] means that job $b$ must be executed before job $a$ can begin.

Return an array representing a valid sequence in which all $n$ jobs can be completed. If multiple valid execution sequences exist, any of them may be returned. If it is impossible to complete all jobs due to cyclic dependencies, return an empty array [].

Constraints

  • $1 \le n \le 2000$
  • $0 \le \text{len}(prerequisites) \le \frac{n(n - 1)}{2}$
  • prerequisites[i] consists of two integers [a, b] where $0 \le a, b < n$ and $a \neq b$.
  • All pairs in prerequisites are distinct.

Examples

Example 1

Input: find_order(2, [[1, 0]])

Output: [0, 1]

Example 2

Input: find_order(4, [[1, 0], [2, 0], [3, 1], [3, 2]])

Output: [0, 1, 2, 3]

Example 3

Input: find_order(2, [[1, 0], [0, 1]])

Output: []

Hints

Hint 1

Think of jobs as vertices in a directed graph and dependencies [a, b] as directed edges from b to a.

Hint 2

Keep track of how many incoming dependencies each job has (its in-degree). Jobs with 0 incoming dependencies can be run immediately.

Hint 3

Process ready jobs one by one, decrementing the dependency count of downstream jobs. If you process all n jobs, you found a valid order; otherwise, a cycle exists.