KatInterview

Teardown Sequencing with Nested Ownership and Extra Prerequisites

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphstopological-sortheapcycle-detection

Last 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 length n. The entry owners[i] is the component that directly contains component i, or -1 if component i is 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 component a must be torn down before component b.

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^4
  • owners[i] == -1 or 0 <= owners[i] < n
  • owners[i] != i
  • 0 <= len(prerequisites) <= 10^5
  • Each pair [a, b] satisfies 0 <= a, b < n and a != 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.