Minimum Build Phases for a Software Dependency Graph
Trees & GraphsAuto-graded · 17 test casesLast updated
Tests whether a candidate can apply topological ordering (Kahn's algorithm / BFS layer-by-layer) to schedule tasks into the fewest sequential build phases.
Minimum Build Phases for a Software Dependency Graph
You are managing a software repository with n modules numbered 0 to n - 1. Some modules depend on others: a dependency [a, b] means module a must finish building before module b can start.
A build phase is a set of modules that can all be built simultaneously — i.e., every module in the phase has all its dependencies satisfied by previously completed phases. Modules in the same phase are built in parallel, so they cannot depend on each other.
Given the number of modules n and a list of dependency pairs, return the minimum number of phases needed to build all modules.
If it is impossible to build all modules (i.e., there is a cycle in the dependency graph), return -1.
Notes
- A module with no dependencies can be built in phase 1.
- Every module must be assigned to exactly one phase.
- The phase number of a module equals
1 + max(phase of all its prerequisites), or1if it has none. - The answer is the maximum phase number assigned to any module.
Constraints
1 ≤ n ≤ 20000 ≤ len(dependencies) ≤ min(n * (n - 1), 4000)- Each dependency is a list
[a, b]with0 ≤ a, b < nanda ≠ b. - There are no duplicate dependency pairs.
- Dependencies are directed:
[a, b]does not imply[b, a].
Examples
Example 1
Input: min_build_phases(4, [[0, 1], [0, 2], [1, 3], [2, 3]])
Output: 3
Example 2
Input: min_build_phases(3, [[0, 1], [1, 2], [2, 0]])
Output: -1
Example 3
Input: min_build_phases(5, [])
Output: 1
Hints
Hint 1
Think about how many 'layers' exist in the dependency DAG — the answer is the length of the longest chain of dependencies plus one.
Hint 2
Try Kahn's algorithm (BFS-based topological sort): process nodes with in-degree 0 first, then reduce in-degrees of their neighbors. Each BFS wave is one phase.
Hint 3
If after processing all reachable nodes some modules are still unvisited, a cycle exists — return -1.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
The minimum number of build phases equals the number of layers in the dependency DAG when processed by Kahn's (BFS-based) topological sort. Equivalently, it is 1 + length_of_longest_dependency_chain.
Each BFS "wave" corresponds to one build phase:
- Phase 1: all modules with no prerequisites (in-degree 0).
- Phase k: all modules whose last unmet prerequisite was completed in phase k-1.
Algorithm (Kahn's BFS with layer counting)
- Build an adjacency list (
adj) and anin_degreearray from the dependency pairs. - Enqueue all nodes with
in_degree == 0. - Process the queue level by level (snapshot the current queue size at the start of each wave):
- Increment
phasesby 1. - For every node in the current wave, decrement the in-degree of its successors; enqueue any that reach 0.
- Increment
- Track
visited(total nodes processed). Ifvisited < nafter BFS finishes, a cycle prevented some nodes from ever reaching in-degree 0 → return-1. - Otherwise return
phases.
Correctness
A node cannot be placed in an earlier phase than its latest prerequisite's phase + 1. BFS ensures every node is placed in the earliest possible phase, so the resulting phase count is minimal.
Cycle Detection
Any cycle creates a group of nodes whose in-degrees never reach 0 (each node in the cycle is blocked by another). The visited != n check detects this precisely.
Complexity
| Time | O(n + E) — each node and edge is processed once |
| Space | O(n + E) — adjacency list + in-degree array + queue |
where E = len(dependencies).
Reference Solution
from typing import List
from collections import deque
def min_build_phases(n: int, dependencies: List[List[int]]) -> int:
adj = [[] for _ in range(n)]
in_degree = [0] * n
for a, b in dependencies:
adj[a].append(b)
in_degree[b] += 1
queue = deque()
for i in range(n):
if in_degree[i] == 0:
queue.append(i)
phases = 0
visited = 0
while queue:
phases += 1
for _ in range(len(queue)):
node = queue.popleft()
visited += 1
for neighbor in adj[node]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)
if visited != n:
return -1
return phases
Worked Example (Sample 1)
n=4, dependencies [[0,1],[0,2],[1,3],[2,3]]
- In-degrees: node 0 → 0, node 1 → 1, node 2 → 1, node 3 → 2
- Phase 1: process node 0 → decrement 1 and 2 to 0
- Phase 2: process nodes 1 and 2 → decrement 3 to 0
- Phase 3: process node 3
Answer: 3