KatInterview

Minimum Build Phases for a Software Dependency Graph

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsgraphstopological sortBFS

Last 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), or 1 if it has none.
  • The answer is the maximum phase number assigned to any module.

Constraints

  • 1 ≤ n ≤ 2000
  • 0 ≤ len(dependencies) ≤ min(n * (n - 1), 4000)
  • Each dependency is a list [a, b] with 0 ≤ a, b < n and a ≠ 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.