Flat-Pack Assembly Order
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
n = 4 rules = [[0, 2], [1, 2], [2, 3]]
[0, 1, 2, 3]
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.
n = 3 rules = [[0, 1], [1, 2], [2, 1]]
[]
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- Hint 1
In the first example, which steps could you do right now? What do they have in common?
- Hint 2
A step is ready when no unfinished step must come before it. Doing a ready step may make others ready.
- Hint 3
For each step, count the rules pointing into it: how many steps it still waits on. When you finish a step, which counts go down?
- Hint 4
Put every step with count 0 in a queue. Repeatedly take one out, add it to the order, and lower the count of each step it points to; a count that hits 0 joins the queue. If the order ends up shorter than
n, the leftover steps wait on each other in a loop: return [].
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.
How to solve it
Treat rules as arrows between steps. A step can go next once every arrow into it comes from a finished step. So count, for each step, the arrows still pointing in, and always pick a step whose count is 0. This is Kahn's algorithm for topological sorting.
Trace the first example, with rules 0→2, 1→2 and 2→3. The counts are 0 for step 0, 0 for step 1, 2 for step 2 and 1 for step 3, so the queue starts with steps 0 and 1.
- Take 0. Order: [0]. Step 2's count drops to 1.
- Take 1. Order: [0, 1]. Step 2 drops to 0 and joins the queue.
- Take 2. Order: [0, 1, 2]. Step 3 drops to 0 and joins.
- Take 3. Order: [0, 1, 2, 3]. All 4 steps are placed.
In the second example, steps 1 and 2 wait on each other. Only step 0 starts with a count of 0, and after it the queue is empty with just 1 of 3 steps placed. An order shorter than n means the rules contain a loop, so the function returns [].
Duplicate rules are harmless: a repeated arrow adds 1 to the count twice and is removed twice.
function assemblyOrder(n, rules) {
const next = Array.from({ length: n }, () => []);
const waiting = new Array(n).fill(0); // rules still pointing into each step
for (const [a, b] of rules) {
next[a].push(b);
waiting[b]++;
}
const queue = [];
for (let s = 0; s < n; s++) if (waiting[s] === 0) queue.push(s);
const order = [];
for (let head = 0; head < queue.length; head++) {
const step = queue[head];
order.push(step);
for (const after of next[step]) {
waiting[after]--;
if (waiting[after] === 0) queue.push(after); // now ready
}
}
return order.length === n ? order : []; // leftovers are stuck in a loop
}from collections import deque
def assembly_order(n, rules):
nxt = [[] for _ in range(n)]
waiting = [0] * n # rules still pointing into each step
for a, b in rules:
nxt[a].append(b)
waiting[b] += 1
queue = deque(s for s in range(n) if waiting[s] == 0)
order = []
while queue:
step = queue.popleft()
order.append(step)
for after in nxt[step]:
waiting[after] -= 1
if waiting[after] == 0:
queue.append(after) # now ready
return order if len(order) == n else [] # leftovers are stuck in a loopRun your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.