Smallest Valid Order for Dependency Forest
Trees & GraphsAuto-graded · 19 test casesLast 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks for a topological ordering of nodes in a directed forest (where edges go from parents to children) that is lexicographically minimized.
- Graph Representation: Build an adjacency list mapping each node to its list of direct children.
- Track Available Nodes: Any node whose parent has already been appended (or any root node with
parents[i] == -1) is "available" to be chosen next. - Greedy Selection with Priority Queue:
- Initialize a min-heap with all root nodes (
parents[i] == -1). - At each step, pop the smallest index from the min-heap and append it to the result list.
- For every child of the popped node, push that child into the min-heap since its predecessor condition has been satisfied.
- Repeat until all nodes have been processed.
- Initialize a min-heap with all root nodes (
Correctness
A standard Depth-First Search (DFS) or Breadth-First Search (BFS) would commit to exploring subtrees or levels in a predetermined order, which can miss overall lexicographically smaller choices across different branches. By maintaining a global min-heap of all unlocked nodes, we ensure that at every position in the output, we greedily pick the candidate with the absolute minimum index currently eligible. Because unlocking a node never restricts previously available candidates, this greedy choice guarantees the lexicographically minimal sequence overall.
Complexity
- Time Complexity: $O(n \log n)$. Each node is pushed and popped from the min-heap exactly once, taking $O(\log n)$ time per node.
- Space Complexity: $O(n)$ to store the adjacency list of children, the min-heap, and the resulting list.
import heapq
from typing import List
def get_lexicographical_lineup(parents: List[int]) -> List[int]:
n = len(parents)
children = [[] for _ in range(n)]
ready = []
for student, parent in enumerate(parents):
if parent == -1:
heapq.heappush(ready, student)
else:
children[parent].append(student)
lineup = []
while ready:
student = heapq.heappop(ready)
lineup.append(student)
for child in children[student]:
heapq.heappush(ready, child)
return lineup