Generate Preorder Depth Forest from Directed Node Pairs
Trees & GraphsAuto-graded · 19 test casesLast updated
Construct a hierarchical forest from directed child-parent relations and output a depth-annotated preorder traversal.
You are given a list of directed structural relationships. Each relation is represented as a pair [child, parent], indicating that child is a direct subordinate of parent.
Your task is to reconstruct the hierarchical forest and output a unified preorder traversal of all trees. Each record in the output must be a two-element list [node_id, depth].
Rules
- Roots & Depths: A root is any node that appears in at least one given relation but is never listed as a
child. Roots have a depth of0. Each non-root node has a depth equal to1 + depth_of_its_parent. - Completeness: Every unique node present across all given pairs must be included in the output exactly once.
- Ordering:
- Primary roots must be processed in ascending numerical order of their IDs.
- For each tree, conduct a preorder depth-first traversal.
- Direct children of any node must be visited in ascending numerical order of their IDs.
Constraints
1 <= len(pairs) <= 10**5- Each pair consists of exactly two integers
[child, parent], where1 <= child, parent <= 10**9. - For each pair,
child != parent. - Each node appears as a
childin at most one pair (i.e., every node has at most one parent). - The directed relations form an acyclic forest.
- Maximum path length from a root to a leaf can be up to
len(pairs).
Examples
Example 1
Input: reporting_forest([[2, 1], [3, 1], [4, 2], [5, 6]])
Output: [[1, 0], [2, 1], [4, 2], [3, 1], [6, 0], [5, 1]]
Example 2
Input: reporting_forest([[9, 7], [7, 3], [4, 3]])
Output: [[3, 0], [4, 1], [7, 1], [9, 2]]
Example 3
Input: reporting_forest([[10, 20]])
Output: [[20, 0], [10, 1]]
Hints
Hint 1
Identify root nodes by collecting all unique node IDs and removing any node that acts as a child in any relationship.
Hint 2
Sort the direct children lists for each parent in ascending order.
Hint 3
Because maximum tree depths can be very large (up to 10^5), avoid deep recursion to prevent stack overflow errors. Use an explicit iterative stack for traversal.
Hint 4
When pushing children onto a LIFO stack for a preorder walk, iterate through children in reverse sorted order so the smallest ID is processed first.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks us to map directed dependencies into a forest structure and output a preorder traversal annotated with node depths.
-
Graph Construction & Identification of Roots:
- Iterate through
pairsto collect every unique node ID present into a setall_nodes. - Maintain a set
child_nodescontaining all nodes that appear as achild. - Build an adjacency map
childrenmapping each parent to its list of direct children. - Any node present in
all_nodesthat is missing fromchild_nodesis a tree root (depth0). Sort these roots in ascending order.
- Iterate through
-
Child Ordering:
- Sort each list of children in
childrenin ascending numerical order.
- Sort each list of children in
-
Iterative Preorder Traversal:
- To avoid system call stack exhaustion caused by linear reporting chains up to $10^5$ nodes deep, perform an iterative DFS using an explicit stack instead of standard recursion.
- For each root, push
(root, 0)onto the stack. - While the stack is non-empty, pop the top element
(curr_node, depth), append[curr_node, depth]to the output list, and examine its children. - Push its direct children onto the stack in reverse sorted order so that the child with the smallest ID sits at the top of the stack and is processed next.
Complexity
- Time Complexity: $\mathcal{O}(N \log N)$ where $N = \text{len(pairs)}$. Processing pairs and populating sets takes $\mathcal{O}(N)$ time. Sorting child lists and the root list takes bounded $\mathcal{O}(N \log N)$ time total. The explicit DFS visits each node and edge exactly once, adding $\mathcal{O}(N)$.
- Space Complexity: $\mathcal{O}(N)$ auxiliary space to store adjacency lists, node sets, the stack, and the result array.
Python Reference Solution
def reporting_forest(pairs: list[list[int]]) -> list[list[int]]:
children = {}
all_nodes = set()
child_nodes = set()
for child, parent in pairs:
all_nodes.add(child)
all_nodes.add(parent)
child_nodes.add(child)
children.setdefault(parent, []).append(child)
for sublist in children.values():
sublist.sort()
roots = sorted(node for node in all_nodes if node not in child_nodes)
result = []
for root in roots:
stack = [(root, 0)]
while stack:
curr_node, depth = stack.pop()
result.append([curr_node, depth])
sub_children = children.get(curr_node)
if sub_children:
for c in reversed(sub_children):
stack.append((c, depth + 1))
return result