Recover Build Order From Incremental Patch Dependencies
Trees & GraphsAuto-graded · 17 test casesLast updated
Tests whether candidates can apply topological sort (Kahn's algorithm or DFS) to determine a valid linear build order from a dependency graph of software patches.
Recover Build Order From Incremental Patch Dependencies
A software release pipeline applies a series of numbered patches to a codebase. Each patch may depend on one or more earlier patches that must be applied first.
You are given:
n— the total number of patches, labeled0throughn - 1.dependencies— a list of pairs[a, b]meaning patchamust be applied before patchb.
Return a list of all patch labels in a valid topological order (i.e., for every dependency [a, b], patch a appears before patch b in the result).
If no valid order exists (i.e., there is a cycle in the dependency graph), return an empty list [].
If multiple valid orderings exist, return the one that is lexicographically smallest (i.e., at each step, choose the smallest-numbered patch that is currently available).
Constraints
1 ≤ n ≤ 20000 ≤ len(dependencies) ≤ min(n * (n - 1), 4000)- Each element of
dependenciesis a pair[a, b]with0 ≤ a, b ≤ n - 1anda ≠ b. - There may be duplicate dependency pairs in the input; treat them as a single dependency.
- Self-loops are not present (
a ≠ bis guaranteed).
Examples
Example 1
Input: build_order(4, [[0, 1], [0, 2], [1, 3], [2, 3]])
Output: [0, 1, 2, 3]
Example 2
Input: build_order(3, [[0, 1], [1, 2], [2, 0]])
Output: []
Example 3
Input: build_order(1, [])
Output: [0]
Hints
Hint 1
Use Kahn's algorithm (BFS-based topological sort): track in-degrees for every node and repeatedly pick the available node with the smallest label.
Hint 2
To always pick the lexicographically smallest available patch, use a min-heap (priority queue) instead of a plain queue.
Hint 3
If the final result contains fewer than n patches, a cycle exists — return [] in that case.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is a direct application of topological sorting with the additional requirement that, among all valid orderings, we must produce the lexicographically smallest one.
Algorithm: Kahn's Algorithm with a Min-Heap
Kahn's algorithm works as follows:
- Build an adjacency list and compute the in-degree (number of prerequisites) for every node.
- Seed a min-heap with all nodes whose in-degree is
0(no prerequisites). - Repeatedly pop the smallest node from the heap, append it to the result, and for each of its neighbors decrement their in-degree. If a neighbor's in-degree drops to
0, push it onto the heap. - After processing, if the result contains all
nnodes, return it. Otherwise a cycle was detected — return[].
Using a min-heap (Python's heapq) instead of a plain queue is what enforces the lexicographically smallest guarantee: at every step we always pick the smallest-indexed available node.
Cycle detection falls out for free: if a cycle exists, the nodes in the cycle will never reach in-degree 0, so the output will be shorter than n.
Deduplication of dependency pairs prevents artificially inflated in-degrees from duplicate edges.
Correctness
- Every node is added to the heap exactly once (when its in-degree reaches 0).
- Each edge is processed exactly once when its source node is popped.
- The min-heap invariant guarantees the lexicographically smallest choice at each step.
- The cycle check (
len(order) == n) is both necessary and sufficient.
Complexity
| Complexity | |
|---|---|
| Time | O((n + E) log n), where E is the number of unique edges — each push/pop on the heap is O(log n) |
| Space | O(n + E) for the adjacency list, in-degree array, and heap |
For the given constraints (n ≤ 2000, E ≤ 4000) this is well within limits.
import heapq
from typing import List
def build_order(n: int, dependencies: List[List[int]]) -> List[int]:
# Deduplicate edges
edges = set(map(tuple, dependencies))
in_degree = [0] * n
adj = [[] for _ in range(n)]
for a, b in edges:
adj[a].append(b)
in_degree[b] += 1
# Min-heap seeded with all nodes that have no prerequisites
heap = [i for i in range(n) if in_degree[i] == 0]
heapq.heapify(heap)
order = []
while heap:
node = heapq.heappop(heap)
order.append(node)
for neighbor in adj[node]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
heapq.heappush(heap, neighbor)
return order if len(order) == n else []