KatInterview

Smallest Valid Order for Dependency Forest

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphstrees-graphsheaps-sortinggreedy-intervals

Last updated

Construct the lexicographically smallest topological ordering of nodes in a forest defined by an ancestor/parent mapping.

You are given an array parents representing a hierarchical dependency structure among $n$ items indexed from $0$ to $n - 1$. For each index $i$, parents[i] indicates the unique direct predecessor of item $i$. If parents[i] == -1, item $i$ has no predecessor and is a root element.

A sequence of all items is considered valid if every predecessor appears strictly earlier in the sequence than all of its descendants.

Find and return the lexicographically smallest valid sequence containing all $n$ items.

Constraints

  • $n = \text{len}(\text{parents})$ where $1 \le n \le 10^5$.
  • For each $i \in [0, n - 1]$, $\text{parents}[i] \in {-1, 0, 1, \dots, n - 1}$.
  • The input describes a valid forest (no cycles).

Examples

Example 1

Input: get_lexicographical_lineup([-1, 0, 0, 1])

Output: [0, 1, 2, 3]

Example 2

Input: get_lexicographical_lineup([1, -1, 1])

Output: [1, 0, 2]

Hints

Hint 1

Consider this as a topological sort task where every parent must be visited prior to its children.

Hint 2

At any given point, which elements are eligible to be chosen next?

Hint 3

To minimize the output sequence lexicographically at each step, always pick the smallest indexed node among all currently available nodes using a priority queue.