Find Build Order With Optional Priorities
Trees & GraphsAuto-graded · 17 test casesLast updated
Tests whether a candidate can produce a valid topological ordering of task dependencies while breaking ties by smallest task ID for determinism.
Build Order Scheduler
You are given a set of tasks numbered from 0 to n - 1 and a list of dependencies. Each dependency [a, b] means task a must be completed before task b can begin.
Your goal is to produce a valid build order: a permutation of all n tasks such that every dependency is respected.
If two or more tasks are equally ready to be scheduled (all their predecessors are already placed), always pick the one with the smallest task ID first. This tie-breaking rule makes the output unique.
If no valid build order exists (i.e., there is a cycle in the dependency graph), return an empty list [].
Function
def build_order(n: int, dependencies: List[List[int]]) -> List[int]:
n— the number of tasks (0-indexed, IDs0throughn-1).dependencies— a list of pairs[a, b]meaning taskamust come before taskb.
Return the unique valid build order produced by always picking the smallest available task ID next, or [] if a cycle exists.
Constraints
1 ≤ n ≤ 2 0000 ≤ len(dependencies) ≤ min(n*(n-1), 4 000)- Each dependency
[a, b]has0 ≤ a, b < nanda ≠ b. - There may be duplicate dependency pairs in the input; treat duplicates as a single constraint.
- There are no guarantees about the input being acyclic.
Examples
Example 1
Input: build_order(4, [[1, 0], [2, 0], [3, 1], [3, 2]])
Output: [3, 1, 2, 0]
Example 2
Input: build_order(3, [[0, 1], [1, 2], [2, 0]])
Output: []
Example 3
Input: build_order(1, [])
Output: [0]
Hints
Hint 1
Think about how many unmet prerequisites each task currently has — a task becomes 'ready' the moment that count drops to zero.
Hint 2
Use a min-heap (priority queue) to always extract the smallest ready task ID in O(log n) time.
Hint 3
If the result list is shorter than n after the algorithm ends, a cycle prevented some tasks from ever becoming ready — return [] in that case.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is a classic topological sort with a deterministic tie-breaking rule: among all currently "ready" tasks, always schedule the one with the smallest ID.
Algorithm (Kahn's / BFS-based topological sort with a min-heap)
- Deduplicate the dependency list to avoid inflating in-degrees.
- Build an adjacency list (
adj[a]holds tasks that depend ona) and an in-degree array (in_degree[b]counts how many predecessorsbstill has). - Push every task with
in_degree == 0into a min-heap — these tasks have no prerequisites and can run immediately. - Repeatedly pop the minimum task from the heap, append it to
order, and for each of its dependents decrement their in-degree. Whenever a dependent's in-degree reaches 0, push it onto the heap. - If
len(order) == nat the end, returnorder; otherwise a cycle prevented some tasks from ever becoming ready, so return[].
Why it is correct
- Kahn's algorithm is a proven method for topological sorting: a node is only scheduled after all its predecessors have been scheduled.
- Using a min-heap instead of a plain queue enforces the smallest-ID-first tie-break, making the output unique.
- A cycle means at least one strongly connected component whose nodes' in-degrees never reach 0, so those nodes never enter the heap — the length check detects this.
Complexity
- Time: O((n + E) log n) where E is the number of unique dependency edges. Each node and edge is processed once; heap operations are O(log n).
- Space: O(n + E) for the adjacency list, in-degree array, and heap.
import heapq
from typing import List
def build_order(n: int, dependencies: List[List[int]]) -> List[int]:
# Deduplicate dependencies
dep_set = set(map(tuple, dependencies))
# Build adjacency list and in-degree count
in_degree = [0] * n
adj = [[] for _ in range(n)]
for a, b in dep_set:
adj[a].append(b)
in_degree[b] += 1
# Seed the min-heap with all tasks that have no prerequisites
heap = [i for i in range(n) if in_degree[i] == 0]
heapq.heapify(heap)
order = []
while heap:
task = heapq.heappop(heap)
order.append(task)
for neighbor in adj[task]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
heapq.heappush(heap, neighbor)
return order if len(order) == n else []