Schedule Tasks with Precedence Constraints
Trees & GraphsAuto-graded · 23 test casesLast 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
prerequisitesare 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.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach: Kahn's Algorithm (BFS Topological Sort)
This problem requires computing a topological ordering of a directed acyclic graph (DAG).
Each dependency pair [a, b] represents a directed edge $b \to a$, indicating that node $b$ must precede node $a$.
We can solve this iteratively using Kahn's Algorithm:
- Graph Construction & In-degree Tracking: Build an adjacency list where
graph[b]stores all tasks dependent on $b$. Maintain anindegreearray whereindegree[a]counts how many unfinished prerequisites task $a$ requires. - Initialize Execution Queue: Add all tasks with
indegree == 0to a queue. These tasks have no remaining prerequisites and can be performed right away. - Iterative Processing:
- Dequeue a task, add it to the final output list.
- For every dependent task connected to it, reduce its
indegreeby 1. - If a dependent task's
indegreefalls to 0, enqueue it.
- Cycle Detection: If the processed output contains all $n$ tasks, return the output array. If fewer than $n$ tasks were processed, at least one cycle exists (preventing involved tasks from ever reaching an in-degree of 0), so return an empty array
[].
Complexity Analysis
- Time Complexity: $\mathcal{O}(V + E)$, where $V = n$ is the number of tasks and $E$ is the number of prerequisite pairs. Every node and edge is traversed once during graph building and queue operations.
- Space Complexity: $\mathcal{O}(V + E)$ to store the adjacency list representation of the graph, the
indegreearray, and the queue.
Python Source Code
from collections import deque
from typing import List
def find_order(n: int, prerequisites: List[List[int]]) -> List[int]:
graph = [[] for _ in range(n)]
indegree = [0] * n
for task, prereq in prerequisites:
graph[prereq].append(task)
indegree[task] += 1
queue = deque(i for i in range(n) if indegree[i] == 0)
order = []
while queue:
curr = queue.popleft()
order.append(curr)
for neighbor in graph[curr]:
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
queue.append(neighbor)
return order if len(order) == n else []