Python coding

Rules that allow only one order

A release has n steps numbered 0 to n - 1. Each pair [first, then] in rules means step first must happen before step then. If exactly one order of all n steps respects every rule, return that order as a list. Otherwise return []: either no order works (the rules contradict each other) or several do.

n ≥ 1; pairs may repeat, rules may be empty, and a rule like [2, 2] (a step before itself) can never be met.

Besides the tests, one large input (2,500 steps, 5,000 rules) with a ~100 ms limit (scaled to your device's speed): brute force won't pass.

  • only_order(3, [[0,1],[1,2]]) → [0,1,2]
  • only_order(3, [[0,1],[0,2]]) → []
  • only_order(4, [[2,0],[0,3],[3,1],[2,3]]) → [2,0,3,1]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Run Kahn's algorithm: count in-degrees, keep the steps that are ready (every step they wait on is placed), place one, release its followers.

Hint 2

If two steps are ready at the same time, either could go first: the order is not unique. If none is ready before all n are placed, there is a cycle.

Solution and why it works
pythonO(n + E), E = len(rules) · O(n + E)
def only_order(n: int, rules: list[list[int]]) -> list[int]:
    after, indeg = [[] for _ in range(n)], [0] * n
    for first, then in rules:
        after[first].append(then)
        indeg[then] += 1
    ready = [i for i in range(n) if indeg[i] == 0]
    order = []
    while len(ready) == 1:                   # two ready steps could swap: not unique
        step = ready.pop()
        order.append(step)
        for nxt in after[step]:
            indeg[nxt] -= 1
            if indeg[nxt] == 0:
                ready.append(nxt)
    return order if len(order) == n else []  # stopped early: a tie or a cycle

Kahn's algorithm places a step only once every rule into it is satisfied, so the steps ready at one moment are exactly those that could come next. Two of them means two valid orders; none before the end means a cycle blocks the rest. The trap is checking only the start: the order can branch later (a chain that splits at the end), so test at every turn, and never return a partial order.