KatInterview

Reconstruct Hierarchical Execution Trees from Trace Records

Trees & GraphsAuto-graded · 15 test cases
MediumAuto-gradedTrees & Graphstreeshash-tablesorting

Last 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, or None if 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:

  1. Every span dictionary in the output should include a new key "children", containing a list of its direct child span dictionaries.
  2. 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.
  3. The root nodes (spans where "parentId" is None) 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.
  4. 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 not None, 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`.