Teardown Sequencing with Nested Ownership and Extra Prerequisites
Trees & GraphsAuto-graded · 20 test casesLast updated
Find the lexicographically smallest valid ordering of nodes under child-before-parent and extra precedence rules, or report impossibility when the rules contradict.
Teardown Sequencing
A platform contains n components numbered 0 through n - 1. Each component may be nested inside one other component, and all components must be torn down one at a time.
You receive:
owners: a list of lengthn. The entryowners[i]is the component that directly contains componenti, or-1if componentiis not contained in anything. A contained component must be torn down before the component that contains it.prerequisites: a list of pairs[a, b]. Each pair means componentamust be torn down before componentb.
Return an ordering of all n components that satisfies every nesting rule and every prerequisite pair.
- If several valid orderings exist, return the lexicographically smallest one. Compare two orderings element by element from the front; the first position where they differ decides, and the ordering with the smaller number there is smaller.
- If no valid ordering exists (the rules contradict each other), return an empty list
[].
Every component must appear exactly once in a valid ordering. If even part of the rules is contradictory, the answer is [] for the whole input.
Repeated rules (for example, a prerequisite pair that duplicates a nesting rule, or the same pair listed twice) are allowed and simply express the same requirement.
Constraints
1 <= n <= 5 * 10^4owners[i] == -1or0 <= owners[i] < nowners[i] != i0 <= len(prerequisites) <= 10^5- Each pair
[a, b]satisfies0 <= a, b < nanda != b
Examples
Example 1
Input: get_teardown_order(4, [1, -1, 3, 1], [[2, 0]])
Output: [2, 0, 3, 1]
Example 2
Input: get_teardown_order(3, [1, 2, 0], [])
Output: []
Hints
Hint 1
Turn every rule into a directed edge from the item that must go first to the item that must go later. Note that for nesting, the edge points from the contained component to its container.
Hint 2
A valid ordering is a topological ordering of this graph. Think about Kahn's algorithm: repeatedly remove a node that has no remaining unmet prerequisites.
Hint 3
To get the lexicographically smallest result, always pick the smallest label among all currently available nodes (use a min-heap). If fewer than n nodes get emitted, there is a cycle, so return []. Be careful that duplicate edges are counted consistently.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model every "must come first" rule as a directed edge a -> b meaning a is torn down before b:
- For each component
iwithowners[i] != -1, add the edgei -> owners[i]. - For each pair
[a, b]inprerequisites, add the edgea -> b.
A valid teardown order is exactly a topological order of this graph, and none exists if the graph has a cycle.
To obtain the lexicographically smallest order, run Kahn's algorithm but keep the ready nodes (in-degree zero) in a min-heap rather than a FIFO queue. Repeatedly pop the smallest ready label, append it to the answer, and decrement the in-degree of each of its successors, pushing any that reach zero.
If the final answer has fewer than n entries, some nodes were never freed, which means a cycle exists, so return [].
Duplicate edges are removed by storing successors in sets and incrementing in-degree only when an edge is new. This keeps the in-degree counts consistent with the edges that get relaxed later.
Why it is correct
- Validity: a node enters the heap only once all its predecessors have been output, so every constraint is respected.
- Cycle detection: nodes on a cycle, and nodes downstream of one, never reach in-degree zero, so they are never emitted and the length check fails.
- Lexicographic minimality: the first element of any valid order must be a currently ready node. Choosing the smallest ready node gives the smallest possible value at that position, and removing a source from an acyclic graph leaves an acyclic graph, so a completion always exists. By induction, every position gets the smallest value achievable given the earlier choices.
Complexity
Let m be the number of edges (at most n + len(prerequisites)).
- Time:
O(m + n log n), since each node is pushed and popped once and each edge is relaxed once. - Space:
O(n + m).
Reference solution
import heapq
from typing import List
def get_teardown_order(n: int, owners: List[int], prerequisites: List[List[int]]) -> List[int]:
graph = [set() for _ in range(n)]
indegree = [0] * n
def add_edge(u: int, v: int) -> None:
if v not in graph[u]:
graph[u].add(v)
indegree[v] += 1
# A contained component must be torn down before its container.
for child, owner in enumerate(owners):
if owner != -1:
add_edge(child, owner)
for a, b in prerequisites:
add_edge(a, b)
ready = [node for node in range(n) if indegree[node] == 0]
heapq.heapify(ready)
order = []
while ready:
node = heapq.heappop(ready)
order.append(node)
for nxt in graph[node]:
indegree[nxt] -= 1
if indegree[nxt] == 0:
heapq.heappush(ready, nxt)
return order if len(order) == n else []