Flat-Pack Assembly Order

Mediumtopological sortAlso known as Course Schedule II

You bought a wardrobe that comes in a flat box. The manual is a mess: instead of numbered pages, it has n steps, numbered 0 to n - 1, and a list of rules like [3, 5], meaning step 3 must be done before step 5 (you cannot hang the doors before the hinges are on).

You want a single order to do all the steps in that breaks no rule. Sometimes the manual contradicts itself, for example step 1 before step 2 and step 2 before step 1. Then no order exists, and you would rather know before you start.

Your task

Write assemblyOrder(n, rules). Return a list containing every step from 0 to n - 1 exactly once, such that for every rule [a, b], step a comes before step b.

If several orders work, return any of them. If no order works, return an empty list [].

assemblyOrder(n: int, rules: int[][]) → int[] Several answers can be correct; any valid one is accepted.

Examples

Example 1
Input
n = 4
rules = [[0, 2], [1, 2], [2, 3]]
Output
[0, 1, 2, 3]
Why

Step 2 needs both 0 and 1 done first, and step 3 needs 2. So 0 and 1 go first in either order, then 2, then 3. [1, 0, 2, 3] is also accepted.

Example 2
Input
n = 3
rules = [[0, 1], [1, 2], [2, 1]]
Output
[]
Why

Step 1 must come before 2, and 2 before 1. No order can do both, so return [].

Constraints

  • 1 ≤ n ≤ 2,000
  • 0 ≤ rules.length ≤ 5,000
  • 0 ≤ a, b < n and a ≠ b
  • The same rule may appear more than once
Start with brute force

Try every ordering of the steps and return the first that breaks no rule.

There are n! orderings. Even 12 steps give about 479 million of them, and n can be 2,000. The rules tell you directly which steps can go next, so there is no need to guess.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code