Reconstruct Hierarchical Execution Trees from Trace Records
Trees & GraphsAuto-graded · 15 test casesLast updated
Reassemble an unordered collection of trace span objects into a forest of child-linked execution trees sorted chronologically.
In distributed tracing systems, execution traces are captured as flat lists of individual operations called spans. Each span is represented as a dictionary containing:
"spanId": A unique identifier (integer or string)."parentId": The identifier of its direct caller, orNoneif it is a root operation."startTime": An integer timestamp indicating when the operation began.
Because trace records can arrive out of order, the input list of spans is unsorted. Your task is to reconstruct the underlying hierarchical execution trees.
Specifically:
- Every span dictionary in the output should include a new key
"children", containing a list of its direct child span dictionaries. - The
"children"list for every node must be ordered in ascending order by"startTime". If multiple siblings share the same"startTime", preserve their original relative order from the input array. - The root nodes (spans where
"parentId"isNone) should be returned as a list. Note that the original ordering of roots must be preserved unless specified, but root nodes themselves should be assembled into trees with sorted children. - Do not mutate the original input dictionaries. Create copies of the dictionaries to append the
"children"key.
Constraints
- $0 \le \text{len}(spans) \le 10,000$
- Every
"spanId"is unique within the list. - If
"parentId"is notNone, it is guaranteed to match a valid"spanId"present in the input list. - All timestamps (
"startTime") are integers.
Output Format
Return a list of root span dictionaries, where each span recursively contains its list of child span dictionaries under the "children" key.
Examples
Example 1
Input: build_span_trees([{'spanId': 1, 'parentId': None, 'startTime': 10}, {'spanId': 2, 'parentId': 1, 'startTime': 20}, {'spanId': 3, 'parentId': 1, 'startTime': 15}])
Output: [{'spanId': 1, 'parentId': None, 'startTime': 10, 'children': [{'spanId': 3, 'parentId': 1, 'startTime': 15, 'children': []}, {'spanId': 2, 'parentId': 1, 'startTime': 20, 'children': []}]}]
Hints
Hint 1
Use a hash map mapping `spanId` to a fresh node copy containing an empty `children` list so you can look up any parent in $O(1)$ time regardless of input ordering.
Hint 2
Perform two passes over the input: first register all nodes in your map, then link each node to its parent's `children` list or add it to your root list.
Hint 3
After linking nodes into a hierarchy, iterate over all created nodes and sort their `children` arrays by `startTime`.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks us to build a hierarchical forest from flat, unsorted trace records with parent-pointer references. Since children can appear before their parents in the input array, we construct the trees in a multi-pass approach using a hash map:
- Mapping Phase: Create a dictionary mapping each
spanIdto a new node dictionary containing all key-value pairs of the original span plus an empty"children"list ([]). Copying each dictionary ensures we do not mutate the input data. - Linking Phase: Iterate through the original spans (or mapped nodes) and use
parentIdto form relationships. IfparentIdisNone, append the node to arootslist. Otherwise, append it tonodes[parentId]["children"]. - Sorting Phase: For every node in our lookup map, sort its
"children"list in ascending order by"startTime". Python'ssortis stable, so elements with identical timestamps preserve their original relative ordering.
Complexity Analysis
- Time Complexity: $\mathcal{O}(N \log N)$ overall. Indexing and linking take $\mathcal{O}(N)$ time. Sorting all children lists across the tree takes $\sum \mathcal{O}(k_i \log k_i)$ where $k_i$ is the number of children of node $i$. Since $\sum k_i \le N$, the total time spent sorting is bounded by $\mathcal{O}(N \log N)$.
- Space Complexity: $\mathcal{O}(N)$ auxiliary memory to store the node lookup table and construct the output trees.
Python Reference Solution
from typing import List
def build_span_trees(spans: List[dict]) -> List[dict]:
nodes = {span["spanId"]: {**span, "children": []} for span in spans}
roots = []
for span in spans:
node = nodes[span["spanId"]]
parent_id = span["parentId"]
if parent_id is None:
roots.append(node)
else:
nodes[parent_id]["children"].append(node)
for node in nodes.values():
node["children"].sort(key=lambda child: child["startTime"])
return roots