Find Valid Completion Sequence for Dependent Tasks
Trees & GraphsAuto-graded · 19 test casesLast updated
Tests understanding of topological sorting, dependency graph modeling, and cycle detection in directed acyclic graphs.
You are given n tasks numbered from 0 to n-1. Some tasks have dependencies: you receive a list prerequisites where each pair [a, b] indicates that task b must finish before task a can begin.
Return any valid sequence in which all n tasks can be completed while respecting every dependency. If no such sequence exists because the dependencies form a cycle, return an empty list.
Constraints:
0 ≤ n ≤ 10⁵0 ≤ prerequisites.length ≤ 10⁵prerequisites[i].length == 20 ≤ a, b < n- All pairs
[a, b]represent valid dependency relationships - A task may depend on itself (which creates a cycle)
- The same dependency pair may appear multiple times
Examples
Example 1
Input: find_task_sequence(4, [[1, 0], [2, 0], [3, 1], [3, 2]])
Output: [0, 1, 2, 3]
Example 2
Input: find_task_sequence(2, [[1, 0], [0, 1]])
Output: []
Example 3
Input: find_task_sequence(3, [])
Output: [0, 1, 2]
Hints
Hint 1
Model the problem as a directed graph where each dependency [a, b] represents an edge from b to a. A valid completion order exists only if the graph contains no cycles.
Hint 2
Consider tracking how many unfinished prerequisites each task has. A task becomes ready to execute once all of its prerequisites are complete.
Hint 3
Use a queue-based approach that processes tasks with zero remaining prerequisites, updating dependent tasks as you go. If you process fewer than n tasks, a cycle must exist.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires finding a topological ordering of a directed graph. Each task is a vertex, and each dependency [a, b] creates a directed edge from b to a (meaning "b unlocks a"). A valid completion sequence exists only when the dependency graph contains no cycles.
We use Kahn's algorithm, which operates on the concept of in-degree:
-
Build the graph: Create an adjacency list where
graph[b]stores all tasks that depend on taskb. Simultaneously track each task's in-degree (the count of unfulfilled prerequisites). -
Initialize with zero-dependency tasks: Add all tasks with in-degree 0 to a queue. These tasks have no prerequisites and can start immediately.
-
Process tasks iteratively: Remove a task from the queue, add it to the output sequence, and decrement the in-degree of every task that depends on it. When a dependent task's in-degree reaches 0, add it to the queue.
-
Detect cycles: If the output sequence contains all
ntasks, we've found a valid ordering. Otherwise, some tasks were never processed, which happens only when they're part of a cycle or depend on a cycle.
Why It Works
A task enters the queue only after all its prerequisites have been processed and added to the sequence. This guarantees that every task appears after all tasks it depends on.
When a cycle exists (such as task x depending on y, y on z, and z on x), none of the tasks in the cycle can ever reach in-degree 0, because each requires another cycle member to complete first. These tasks remain unprocessed, so the final sequence length is less than n.
Complexity
-
Time: O(n + E) where E is the number of prerequisite pairs. We build the graph in O(E) time, initialize the queue in O(n) time, and then process each task and each edge exactly once.
-
Space: O(n + E) for the adjacency list, in-degree array, queue, and output sequence.
from collections import deque
from typing import List
def find_task_sequence(n: int, prerequisites: List[List[int]]) -> List[int]:
# Build adjacency list: graph[b] contains all tasks that depend on b
graph = [[] for _ in range(n)]
indegree = [0] * n
for a, b in prerequisites:
graph[b].append(a)
indegree[a] += 1
# Start with tasks that have no prerequisites
queue = deque(i for i in range(n) if indegree[i] == 0)
sequence = []
while queue:
current = queue.popleft()
sequence.append(current)
# Process all tasks that depend on the current task
for dependent in graph[current]:
indegree[dependent] -= 1
if indegree[dependent] == 0:
queue.append(dependent)
# If we couldn't process all tasks, a cycle exists
return sequence if len(sequence) == n else []