Flat-Pack Assembly Order

Mediumtopological sortAlso known as Course Schedule II

Your flat-pack wardrobe's manual has n steps, numbered 0 to n - 1, plus rules like [3, 5]: step 3 before step 5 (hinges before doors). You want one order that breaks no rule. If the manual contradicts itself, say step 1 before 2 and 2 before 1, 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 0 and 1 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 and return the first that breaks no rule. There are n! orderings: about 479 million for just 12 steps, and n can be 2,000. The rules already tell you 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