Rank Build Targets by Dependency Order
Trees & GraphsAuto-graded · 17 test casesLast updated
Tests whether a candidate can produce a valid topological ordering of a build-dependency DAG and apply a precise tie-break rule when multiple orderings exist.
Rank Build Targets by Dependency Order
You are given a list of build targets (each identified by a unique string name) and a list of dependency pairs. A pair [A, B] means target A must be built before target B.
Write a function that returns a valid topological ordering of all targets. If the dependency graph contains a cycle, return an empty list instead.
Tie-break rule (important for judging)
Whenever more than one target has no remaining unmet dependencies and is therefore ready to be scheduled next, always pick the one that comes first in lexicographic (alphabetical) order. This makes the output unique and deterministic.
Details
- Every target that appears anywhere (either as a standalone target in
targetsor inside a dependency pair) must appear exactly once in the output when no cycle exists. - The
targetslist declares all nodes; dependency pairs only reference names already intargets. - There are no self-loops in the input (a target will never depend on itself).
- If
targetsis empty, return[].
Constraints
0 ≤ len(targets) ≤ 2 0000 ≤ len(deps) ≤ 10 000- Each target name is a non-empty string of lowercase letters and digits, length ≤ 20.
- All target names are distinct.
- Dependency pairs reference only names present in
targets. - No duplicate dependency pairs.
Examples
Example 1
Input: build_order(['alpha', 'beta', 'gamma', 'delta'], [['alpha', 'beta'], ['alpha', 'gamma'], ['beta', 'delta'], ['gamma', 'delta']])
Output: ['alpha', 'beta', 'gamma', 'delta']
Example 2
Input: build_order(['lib', 'app', 'test', 'core'], [['core', 'lib'], ['core', 'app'], ['lib', 'app'], ['app', 'test']])
Output: ['core', 'lib', 'app', 'test']
Example 3
Input: build_order(['x', 'y', 'z'], [['x', 'y'], ['y', 'z'], ['z', 'x']])
Output: []
Hints
Hint 1
Try Kahn's algorithm (BFS-based topological sort): maintain a queue of nodes whose in-degree has reached zero and process them one at a time.
Hint 2
To enforce the tie-break, use a min-heap (priority queue) instead of a plain queue so that among all currently ready nodes you always pick the lexicographically smallest one.
Hint 3
If the result list has fewer entries than the number of targets after the algorithm finishes, a cycle exists — return [] in that case.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
A topological ordering processes each node only after all its prerequisites have been handled. Kahn's algorithm achieves this by repeatedly removing nodes with in-degree zero (no remaining unmet dependencies). To make the result unique, we impose the tie-break: when multiple nodes are simultaneously ready, always choose the lexicographically smallest name.
Algorithm
- Build the graph: create an adjacency list (
adj[A]lists all targets that depend on A) and compute the in-degree of every target. - Initialize a min-heap with all targets whose in-degree is 0. A min-heap gives O(log n) extraction of the lexicographically smallest element.
- Process: repeatedly pop the smallest ready node, append it to the result, and decrement the in-degree of each of its neighbors. When a neighbor's in-degree drops to 0, push it onto the heap.
- Cycle detection: if the result list is shorter than the total number of targets, at least one cycle exists — return
[].
Correctness
- Every node is added to the heap exactly once (when its in-degree first hits 0), so no node is processed twice.
- A node is processed only after all its predecessors have been processed (their edges have been "removed" by decrementing in-degrees), guaranteeing a valid topological order.
- The min-heap tie-break ensures a unique, deterministic output.
Complexity
| Value | |
|---|---|
| Time | O((V + E) log V) — each of the V heap insertions/extractions costs O(log V); each of the E edges is relaxed once |
| Space | O(V + E) — adjacency list and in-degree map |
where V = number of targets, E = number of dependency pairs.
Reference Solution
import heapq
from typing import List
from collections import defaultdict
def build_order(targets: List[str], deps: List[List[str]]) -> List[str]:
if not targets:
return []
# Build adjacency list and in-degree map
in_degree = {t: 0 for t in targets}
adj = defaultdict(list)
for a, b in deps:
adj[a].append(b)
in_degree[b] += 1
# Seed the min-heap with all zero-in-degree nodes
heap = [t for t in targets if in_degree[t] == 0]
heapq.heapify(heap)
result = []
while heap:
node = heapq.heappop(heap)
result.append(node)
for neighbor in adj[node]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
heapq.heappush(heap, neighbor)
# If not all nodes were processed, there is a cycle
if len(result) != len(targets):
return []
return result