All problems
0013MediumDepth-First SearchBreadth-First SearchGraph TheoryTopological Sort

Module Build Order

Tracked in this browser only
Write code

Trains the technique from

LeetCode 210Course Schedule II

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A release engineer compiles a project whose moduleCount modules are labelled 0 through moduleCount - 1. Each module is compiled exactly once. Every entry [x, y] of dependencies says that module y has to finish compiling before module x may start.

Plenty of sequences can satisfy the same dependency set, so the build tool fixes one: whenever more than one module is unblocked, it always takes the lowest-numbered candidate. That rule makes the answer the lexicographically smallest valid sequence. Return that sequence.

If the dependencies leave no way to compile every module, return an empty array.

Examples

Example 1

Input
moduleCount = 3, dependencies = [[1, 0]]
Output
[0, 1, 2]

Module 0 gates module 1 while module 2 is free from the start, and always grabbing the lowest unblocked label produces 0, 1, 2.

Example 2

Input
moduleCount = 5, dependencies = [[2, 0], [3, 2], [1, 3], [4, 1]]
Output
[0, 2, 3, 1, 4]

The entries chain the modules single file, so only one sequence exists no matter which candidate rule is applied.

Example 3

Input
moduleCount = 2, dependencies = [[0, 1], [1, 0]]
Output
[]

Each of the two modules waits on the other, so neither can ever start and the array comes back empty.

Constraints

  • 1 <= moduleCount <= 2000
  • 0 <= dependencies.length <= moduleCount * (moduleCount - 1)
  • dependencies[i].length == 2
  • 0 <= x, y < moduleCount
  • x != y
  • No pair [x, y] is repeated
  • Among all valid sequences, return the lexicographically smallest

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def build_order(moduleCount: int, dependencies: list[list[int]]) -> list[int]:
Java
public int[] buildOrder(int moduleCount, int[][] dependencies)
September 7
Apply