KatInterview

Smallest-Label Build Sequence with Cycle Check

Trees & GraphsAuto-graded · 27 test cases
MediumAuto-gradedTrees & Graphstopological-sortheapgraph

Last updated

Produce the lexicographically smallest valid ordering of a dependency graph using a min-heap variant of Kahn's algorithm, returning an empty list if a cycle makes ordering impossible.

Build Sequence Planner

A build system has n modules numbered 0 through n - 1. You are given a list prereqs of directed pairs. A pair [a, b] means module a must be built strictly before module b.

A build sequence is an arrangement of all n modules, each appearing exactly once, such that for every pair [a, b] in prereqs, module a comes earlier than module b.

Return the build sequence that is lexicographically smallest. That is, if you compare two valid sequences position by position, the one with the smaller number at the first differing position wins.

If no valid build sequence exists because the dependencies contain a cycle, return an empty list [].

Rules and edge cases

  • prereqs may contain the same pair more than once. Repeated pairs describe the same single dependency and do not change the answer.
  • prereqs may contain a pair like [a, a]. A module cannot be built before itself, so this makes a valid sequence impossible and the result is [].
  • Modules that appear in no pair are still part of the sequence and must be placed like any other module.
  • A cycle in any part of the graph makes the whole answer [], even if other parts could be ordered.

Constraints

  • 1 <= n <= 10^5
  • 0 <= len(prereqs) <= 2 * 10^5
  • 0 <= a, b < n for every pair [a, b] in prereqs

Examples

Example 1

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

Output: [3, 1, 2, 0]

Example 2

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

Output: []

Example 3

Input: smallest_build_sequence(5, [[0, 2], [0, 2], [1, 3]])

Output: [0, 1, 2, 3, 4]

Hints

Hint 1

At any moment, which modules are allowed to be placed next? Only those whose prerequisites have all been placed already.

Hint 2

Among the modules that are currently allowed, which one should you choose to make the sequence as small as possible at this position? Think about what data structure gives you the minimum quickly.

Hint 3

Track how many unplaced prerequisites each module has. If you finish with fewer than n modules placed, some modules were never released, which means there is a cycle (self-pairs included).