Determine Build Task Schedule
Trees & GraphsAuto-graded · 23 test casesLast updated
Find a valid topological sequence for tasks with prerequisite constraints or detect cyclic dependencies.
You are given a list of task names and a list of direct dependency constraints between tasks. Each dependency constraint is represented as a pair [A, B], which indicates that task A depends on task B (meaning task B must complete before task A can begin).
Determine a valid execution sequence for all tasks that honors all dependency constraints. If multiple valid execution sequences exist, any valid sequence is acceptable. If a valid schedule is impossible due to circular dependencies, return None.
Constraints
1 <= len(pipelines) <= 10000 <= len(dependencies) <= 5000- Task names are non-empty strings.
- All task names listed in
dependenciesare guaranteed to exist inpipelines. - Input dependency lists may contain duplicate dependency pairs.
Examples
Example 1
Input: pipeline_execution_order(['P1', 'P2', 'P3'], [['P1', 'P2'], ['P3', 'P2']])
Output: ['P2', 'P1', 'P3']
Example 2
Input: pipeline_execution_order(['A', 'B', 'C', 'D'], [['B', 'A'], ['C', 'A'], ['D', 'B'], ['D', 'C']])
Output: ['A', 'B', 'C', 'D']
Example 3
Input: pipeline_execution_order(['build', 'test', 'deploy'], [['test', 'build'], ['deploy', 'test']])
Output: ['build', 'test', 'deploy']
Hints
Hint 1
Model the tasks as nodes in a directed graph where an edge points from a prerequisite to a dependent task.
Hint 2
Use topological sorting algorithms like Kahn's algorithm (BFS using in-degrees) or standard depth-first search (DFS).
Hint 3
If the processed output contains fewer tasks than the total list, a cycle exists.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem can be solved by representing tasks as nodes in a directed graph. A dependency [A, B] implies a directed edge from B to A ($B \rightarrow A$), signaling that $B$ must precede $A$. Finding a valid schedule corresponds to finding a topological sort of this directed graph.
We can use Kahn's Algorithm (a BFS-based approach):
- In-degree Calculation & Adjacency List: Compute the in-degree (number of incoming edges / unmet prerequisites) for each task. Build an adjacency list mapping each task to the list of tasks dependent on it.
- Initialize Queue: Enqueue all tasks with an in-degree of
0(tasks with no prerequisites). - Process Graph: Pop a task from the queue, append it to the result list, and decrement the in-degree of all its downstream dependents. Whenever a dependent's in-degree reaches
0, push it to the queue. - Cycle Detection: If the final result list contains all tasks, we have successfully found a valid execution order. If the result list has fewer elements than the total number of tasks, a cycle exists in the graph, making execution impossible; return
None.
Complexity
- Time Complexity: $O(V + E)$ where $V$ is the number of tasks (
pipelines) and $E$ is the number of dependencies (dependencies). Each vertex and directed edge is processed once. - Space Complexity: $O(V + E)$ to store the graph adjacency structure, in-degrees, queue, and output order.
Python Reference Solution
from typing import List, Optional
from collections import deque, defaultdict
def pipeline_execution_order(pipelines: List[str], dependencies: List[List[str]]) -> Optional[List[str]]:
graph = defaultdict(list)
in_degree = {p: 0 for p in pipelines}
for dependent, prerequisite in dependencies:
graph[prerequisite].append(dependent)
in_degree[dependent] += 1
queue = deque([p for p in pipelines if in_degree[p] == 0])
result = []
while queue:
current = queue.popleft()
result.append(current)
for neighbor in graph[current]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)
return result if len(result) == len(pipelines) else None