Smallest-Label Build Sequence with Cycle Check
Trees & GraphsAuto-graded · 27 test casesLast updated
Produce the lexicographically smallest valid ordering of a dependency graph using a min-heap variant of Kahn's algorithm, returning an empty list if a cycle makes ordering impossible.
Build Sequence Planner
A build system has n modules numbered 0 through n - 1. You are given a list prereqs of directed pairs. A pair [a, b] means module a must be built strictly before module b.
A build sequence is an arrangement of all n modules, each appearing exactly once, such that for every pair [a, b] in prereqs, module a comes earlier than module b.
Return the build sequence that is lexicographically smallest. That is, if you compare two valid sequences position by position, the one with the smaller number at the first differing position wins.
If no valid build sequence exists because the dependencies contain a cycle, return an empty list [].
Rules and edge cases
prereqsmay contain the same pair more than once. Repeated pairs describe the same single dependency and do not change the answer.prereqsmay contain a pair like[a, a]. A module cannot be built before itself, so this makes a valid sequence impossible and the result is[].- Modules that appear in no pair are still part of the sequence and must be placed like any other module.
- A cycle in any part of the graph makes the whole answer
[], even if other parts could be ordered.
Constraints
1 <= n <= 10^50 <= len(prereqs) <= 2 * 10^50 <= a, b < nfor every pair[a, b]inprereqs
Examples
Example 1
Input: smallest_build_sequence(4, [[1, 0], [2, 0], [3, 1], [3, 2]])
Output: [3, 1, 2, 0]
Example 2
Input: smallest_build_sequence(3, [[0, 1], [1, 2], [2, 0]])
Output: []
Example 3
Input: smallest_build_sequence(5, [[0, 2], [0, 2], [1, 3]])
Output: [0, 1, 2, 3, 4]
Hints
Hint 1
At any moment, which modules are allowed to be placed next? Only those whose prerequisites have all been placed already.
Hint 2
Among the modules that are currently allowed, which one should you choose to make the sequence as small as possible at this position? Think about what data structure gives you the minimum quickly.
Hint 3
Track how many unplaced prerequisites each module has. If you finish with fewer than n modules placed, some modules were never released, which means there is a cycle (self-pairs included).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is Kahn's topological sort, but the pool of "ready" modules is a min-heap instead of a FIFO queue.
- Remove duplicate pairs, then build an adjacency list and count, for each module, how many distinct prerequisites it has (its in-degree).
- Put every module with in-degree 0 into a min-heap.
- Repeatedly pop the smallest module from the heap and append it to the result. For each module that depends on it, decrement its in-degree; when that reaches 0, push it onto the heap.
- If the result contains all
nmodules, return it. Otherwise return[].
Why it is correct
- Only ready modules can come next. A module that still has an unplaced prerequisite cannot legally occupy the next position, so the candidates for each position are exactly the modules in the heap.
- Choosing the smallest ready module is optimal. With a fixed prefix, the smallest value that can appear at the next position is the smallest ready label. Lexicographic order is decided by the earliest differing position, so taking that minimum at every step gives the smallest sequence. Picking any ready module never causes a dead end in an acyclic graph, because the remaining graph is still acyclic, so a completion always exists.
- Cycle detection. Modules on a cycle, or downstream of one, never reach in-degree 0 and are never placed. So the result is shorter than
nexactly when a cycle exists. A self-pair[a, a]givesaan in-degree that can never be cleared, so it is handled the same way. - Duplicates. Deduplicating means each dependency is counted once. (Even without it, each copy would be both counted and decremented, giving the same result.)
Complexity
Let m = len(prereqs).
- Time:
O(n log n + m). Each module is pushed and popped at most once, and each distinct pair is processed once. - Space:
O(n + m)for the adjacency list, in-degree array, dedup set, heap, and output.
Reference solution
import heapq
from typing import List
def smallest_build_sequence(n: int, prereqs: List[List[int]]) -> List[int]:
adj = [[] for _ in range(n)]
indegree = [0] * n
seen = set()
for a, b in prereqs:
if (a, b) in seen:
continue
seen.add((a, b))
adj[a].append(b)
indegree[b] += 1
heap = [i for i in range(n) if indegree[i] == 0]
heapq.heapify(heap)
order = []
while heap:
cur = heapq.heappop(heap)
order.append(cur)
for nxt in adj[cur]:
indegree[nxt] -= 1
if indegree[nxt] == 0:
heapq.heappush(heap, nxt)
return order if len(order) == n else []