KatInterview

Rank Build Targets by Dependency Order

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

Last 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 targets or inside a dependency pair) must appear exactly once in the output when no cycle exists.
  • The targets list declares all nodes; dependency pairs only reference names already in targets.
  • There are no self-loops in the input (a target will never depend on itself).
  • If targets is empty, return [].

Constraints

  • 0 ≤ len(targets) ≤ 2 000
  • 0 ≤ 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.