KatInterview

Find Build Order With Optional Priorities

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

Last updated

Tests whether a candidate can produce a valid topological ordering of task dependencies while breaking ties by smallest task ID for determinism.

Build Order Scheduler

You are given a set of tasks numbered from 0 to n - 1 and a list of dependencies. Each dependency [a, b] means task a must be completed before task b can begin.

Your goal is to produce a valid build order: a permutation of all n tasks such that every dependency is respected.

If two or more tasks are equally ready to be scheduled (all their predecessors are already placed), always pick the one with the smallest task ID first. This tie-breaking rule makes the output unique.

If no valid build order exists (i.e., there is a cycle in the dependency graph), return an empty list [].

Function

def build_order(n: int, dependencies: List[List[int]]) -> List[int]:
  • n — the number of tasks (0-indexed, IDs 0 through n-1).
  • dependencies — a list of pairs [a, b] meaning task a must come before task b.

Return the unique valid build order produced by always picking the smallest available task ID next, or [] if a cycle exists.

Constraints

  • 1 ≤ n ≤ 2 000
  • 0 ≤ len(dependencies) ≤ min(n*(n-1), 4 000)
  • Each dependency [a, b] has 0 ≤ a, b < n and a ≠ b.
  • There may be duplicate dependency pairs in the input; treat duplicates as a single constraint.
  • There are no guarantees about the input being acyclic.

Examples

Example 1

Input: build_order(4, [[1, 0], [2, 0], [3, 1], [3, 2]])

Output: [3, 1, 2, 0]

Example 2

Input: build_order(3, [[0, 1], [1, 2], [2, 0]])

Output: []

Example 3

Input: build_order(1, [])

Output: [0]

Hints

Hint 1

Think about how many unmet prerequisites each task currently has — a task becomes 'ready' the moment that count drops to zero.

Hint 2

Use a min-heap (priority queue) to always extract the smallest ready task ID in O(log n) time.

Hint 3

If the result list is shorter than n after the algorithm ends, a cycle prevented some tasks from ever becoming ready — return [] in that case.