KatInterview

Recover Build Order From Incremental Patch Dependencies

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

Last 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, labeled 0 through n - 1.
  • dependencies — a list of pairs [a, b] meaning patch a must be applied before patch b.

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 ≤ 2000
  • 0 ≤ len(dependencies) ≤ min(n * (n - 1), 4000)
  • Each element of dependencies is a pair [a, b] with 0 ≤ a, b ≤ n - 1 and a ≠ b.
  • There may be duplicate dependency pairs in the input; treat them as a single dependency.
  • Self-loops are not present (a ≠ b is 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.