Reconstruct Call Trees from Shuffled Spans

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Telemetry agents across microservices report call records (spans) in arbitrary arrival order, so downstream sub-calls frequently appear in a batch ahead of the caller that spawned them.

You are given spans, a flat list of span dictionaries. Every dictionary contains:

  • "spanId" (int or str): unique identifier for this call record (note that 0 and "" are valid identifiers).
  • "parentId" (int, str, or None, optional): identifier of the enclosing caller span. When "parentId" is None—or when the "parentId" key is omitted altogether—the record represents a top-level root trace.
  • "startTime" (int): timestamp indicating when the call began.
  • Optional extra metadata keys (such as "name"), which must be preserved verbatim.

Implement build_span_trees(spans) to assemble these flat records into a forest of nested dictionaries and return the list of root span dictionaries:

  1. Every returned node (including leaves) must copy all keys from its input dictionary and include a "children" key holding a list of its direct child nodes ([] when a span has no children).
  2. At every level of every tree, each node's "children" list must be ordered by ascending "startTime" (preserving relative input order when sibling "startTime" values tie).
  3. Do not mutate the dictionaries inside the caller's spans list.

Examples

Example 1

spans = [
    {"spanId": 102, "parentId": 100, "startTime": 45},
    {"spanId": 100, "parentId": None, "startTime": 12},
    {"spanId": 101, "parentId": 100, "startTime": 28},
]

Output:

[
    {
        "spanId": 100,
        "parentId": None,
        "startTime": 12,
        "children": [
            {"spanId": 101, "parentId": 100, "startTime": 28, "children": []},
            {"spanId": 102, "parentId": 100, "startTime": 45, "children": []},
        ],
    }
]

Span 100 has parentId = None, making it the sole root. Even though 102 appeared first in spans, 101 (startTime = 28) precedes 102 (startTime = 45) inside 100's "children" list.

Example 2

spans = [
    {"spanId": "db-read", "parentId": "auth", "startTime": 32},
    {"spanId": "cache", "parentId": "gateway", "startTime": 18},
    {"spanId": "gateway", "parentId": None, "startTime": 5},
    {"spanId": "auth", "parentId": "gateway", "startTime": 25},
]

Output:

[
    {
        "spanId": "gateway",
        "parentId": None,
        "startTime": 5,
        "children": [
            {"spanId": "cache", "parentId": "gateway", "startTime": 18, "children": []},
            {
                "spanId": "auth",
                "parentId": "gateway",
                "startTime": 25,
                "children": [
                    {"spanId": "db-read", "parentId": "auth", "startTime": 32, "children": []}
                ],
            },
        ],
    }
]

"gateway" is the root; its two direct children "cache" (18) and "auth" (25) are ordered by "startTime", and "db-read" (32) nests underneath "auth".

Constraints

  • 0 <= len(spans) <= 10,000
  • Every "spanId" in spans is unique (int or str).
  • Every non-None "parentId" matches the "spanId" of another entry in spans, and parent links form an acyclic forest.
  • "startTime" is an integer (note: due to server clock skew, a child's "startTime" may be smaller than its parent's "startTime").

Step-by-step walkthrough

  1. Understand the goal and input shape

    Across microservices, a single incoming request may fan out to caches, auth services, and databases. Tracing agents emit each sub-call as a span—a dictionary carrying a unique spanId, an optional parentId naming the caller span, and an integer startTime. Because hosts flush batches independently, records arrive shuffled: child calls routinely appear in spans ahead of their parents.

    We need to convert that flat batch into a forest of nested dictionaries (one tree per root span):

    • A root is any record whose parentId is None (or omitted completely).
    • Every output node preserves all original keys of its span plus "children": [...] ([] on leaves).
    • Every "children" list is ordered by ascending startTime.
    Shuffled input records (Example 1):
      {"spanId": 102, "parentId": 100,  "startTime": 45}
      {"spanId": 100, "parentId": None, "startTime": 12}
      {"spanId": 101, "parentId": 100,  "startTime": 28}
    
    Target nested tree (children of 100 ordered by startTime: 28 before 45):
      span 100 (t=12)
      ├── span 101 (t=28, children=[])
      └── span 102 (t=45, children=[])
    

    Two details are helpful to keep in mind:

    • Order of roots: Any ordering of multiple top-level roots is valid, though sorting upfront naturally orders roots by startTime too.
    • Tied startTime values: Python's built-in sorted() is stable, so siblings with identical startTime preserve their relative input order.
  2. Why a naive top-down search hits two walls

    A tempting first idea is to locate every root record, scan the entire spans list to gather records whose parentId matches that root's spanId, sort those children by startTime, and recurse downward.

    At n = 10,000 spans, that top-down approach breaks in two ways:

    1. Quadratic runtime (O(n^2)): Scanning all n records for each of the n nodes performs 10,000 * 10,000 = 100,000,000 checks.
    2. Call-stack overflow: A 10,000-span chain 0 -> 1 -> 2 -> ... -> 9999 recurses 10,000 levels deep, exceeding Python's ~1,000-frame recursion limit with RecursionError.

    Both obstacles vanish once we invert the lookup: rather than making each parent hunt through the list for its children, let each child jump straight to its parent in a dictionary.

  3. Key idea: index by `spanId` first, then link in `startTime` order

    We can wire the entire forest using flat loops and zero recursion:

    1. Allocate node copies upfront (O(n)): Copy every record into a dictionary nodes[span_id] with a fresh "children": [] list. Because all nodes exist before any parent-child edge is wired, input order between parents and children no longer matters.
    2. Sort records once by startTime (O(n log n)): Build a chronologically ordered list sorted_spans.
    3. Wire each node to its parent (O(n)): Sweep sorted_spans from smallest startTime to largest, fetch nodes[parent_id] in O(1) time, and append node to parent_node["children"] (or to roots when parent_id is None).

    Why does one global sort order every "children" list at every tree depth? Because we visit spans in non-decreasing startTime order, each .append(node) adds a child whose startTime is greater than or equal to every sibling already appended to that parent!

    Phase 1 — Populate `nodes` dictionary:
      nodes[102] -> {spanId: 102, startTime: 45, children: []}
      nodes[100] -> {spanId: 100, startTime: 12, children: []}
      nodes[101] -> {spanId: 101, startTime: 28, children: []}
    
    Phase 2 & 3 — Sweep in startTime order [100 (t=12), 101 (t=28), 102 (t=45)]:
      visit 100 (parent None) -> roots = [nodes[100]]
      visit 101 (parent 100)  -> nodes[100]["children"] = [nodes[101]]
      visit 102 (parent 100)  -> nodes[100]["children"] = [nodes[101], nodes[102]]
    

    Because Python lists hold object references, appending nodes["auth"] into nodes["gateway"]["children"] automatically carries along any nested descendants attached to nodes["auth"], even when clock skew causes a child to have an earlier startTime than its parent.

  4. Phase 1: create clean node copies in a hash map

    Using dict(span) makes a shallow copy of each input record. That retains extra fields (like "name") while keeping the caller's input dictionaries untouched. A small helper _get_start_time keeps the sort key clear.

    from typing import Any, Dict, List
    
    
    def _get_start_time(span: dict) -> int:
        """Return a span's startTime for chronological sorting."""
        return span["startTime"]
    
    
    def create_nodes(spans: List[dict]) -> Dict[Any, dict]:
        # nodes: dict mapping span_id -> {"spanId": ..., "parentId": ..., "startTime": ..., "children": []}
        nodes: Dict[Any, dict] = {}
        for span in spans:
            node = dict(span)
            node["children"] = []
            span_id = span["spanId"]
            nodes[span_id] = node
        return nodes
    
  5. Phase 2 & 3: sort chronologically and wire parents

    Watch out for two subtle Python traps when reading "parentId":

    • Read with span.get("parentId") rather than span["parentId"]: Because "parentId" is optional on roots, a root dictionary may omit the key entirely; .get("parentId") returns None cleanly.
    • Check parent_id is None, never if not parent_id:: Both 0 and "" are falsy in Python! Writing if not parent_id: detaches children of span 0 and turns them into bogus roots.

    We also include parent_id not in nodes as a defensive fallback so an incomplete trace with a missing parent never raises KeyError.

    def link_sorted_spans(spans: List[dict], nodes: dict) -> List[dict]:
        sorted_spans = sorted(spans, key=_get_start_time)
    
        roots: List[dict] = []
        for span in sorted_spans:
            span_id = span["spanId"]
            node = nodes[span_id]
            parent_id = span.get("parentId")
    
            if parent_id is None or parent_id not in nodes:
                roots.append(node)
            else:
                parent_node = nodes[parent_id]
                parent_node["children"].append(node)
    
        return roots
    
  6. Trace Example 2 (three-level string IDs)

    Let's walk through Example 2 where children and grandchildren precede "gateway" in spans:

    Input spans:
      {"spanId": "db-read", "parentId": "auth",    "startTime": 32}
      {"spanId": "cache",   "parentId": "gateway", "startTime": 18}
      {"spanId": "gateway", "parentId": None,      "startTime": 5}
      {"spanId": "auth",    "parentId": "gateway", "startTime": 25}
    
    1. Phase 1 populates `nodes` for "db-read", "cache", "gateway", "auth" with children = [].
    
    2. Phase 2 sorts by startTime -> ["gateway" (5), "cache" (18), "auth" (25), "db-read" (32)].
    
    3. Phase 3 wires references in sorted order:
       - "gateway" (t=5,  parent=None):      roots = [nodes["gateway"]]
       - "cache"   (t=18, parent="gateway"): gateway.children = [cache]
       - "auth"    (t=25, parent="gateway"): gateway.children = [cache, auth]
       - "db-read" (t=32, parent="auth"):    auth.children = [db-read]
    
    Final tree at roots[0]:
      gateway (t=5) -> children: [cache (t=18), auth (t=25) -> children: [db-read (t=32)]]
    

    Every level is sorted by startTime, every leaf carries "children": [], and zero recursion was needed.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def _get_start_time(span: dict) -> int:
        """Return a span's startTime for chronological sorting."""
        return span["startTime"]
    
    
    def build_span_trees(spans: List[dict]) -> List[dict]:
        # Phase 1: Create one output node per span in a hash map keyed by spanId.
        # nodes: dict mapping span_id -> {"spanId": ..., "parentId": ..., "startTime": ..., "children": []}
        # Copying with dict(span) preserves extra fields without mutating the caller's input dicts.
        nodes: Dict[Any, dict] = {}
        for span in spans:
            node = dict(span)
            node["children"] = []
            span_id = span["spanId"]
            nodes[span_id] = node
    
        # Phase 2: Sort all spans by startTime ascending before linking.
        # Because we append children in startTime order, every parent's "children" list
        # (and the top-level roots list) ends up sorted automatically without per-node sorts.
        sorted_spans = sorted(spans, key=_get_start_time)
    
        # Phase 3: Attach each node to its parent's "children" list, or collect it as a root.
        # roots: list of root node dicts (each containing nested "children" lists)
        roots: List[dict] = []
        for span in sorted_spans:
            span_id = span["spanId"]
            node = nodes[span_id]
            # Use .get("parentId") because a root span may omit the "parentId" key completely.
            parent_id = span.get("parentId")
    
            # Check `parent_id is None` rather than `not parent_id` because 0 and "" are valid spanIds.
            # If parent_id is absent from nodes (defensive guard for truncated traces), treat as a root.
            if parent_id is None or parent_id not in nodes:
                roots.append(node)
            else:
                parent_node = nodes[parent_id]
                parent_node["children"].append(node)
    
        return roots
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of assembling a company org chart from a shuffled box of employee index cards, where each card lists an employee ID, a manager ID, and a hire timestamp. If you pick up a manager's card and riffle through the entire box from front to back to find every direct report, you end up scanning thousands of cards repeatedly. Instead, lay a folder on a table for every employee indexed by ID (a hash map, a key-value lookup table that fetches any entry by key in O(1) average time). Once every folder exists, sort the cards chronologically and drop each employee's folder straight into their manager's folder—filling every manager's direct-report list in timestamp order automatically.

The naive top-down strategy—scanning all n records to locate each span's children and recursing downward—breaks in two ways at n = 10,000. First, scanning n records for each of the n nodes performs n^2 = 100,000,000 checks rather than n dictionary lookups. Second, when a trace forms a single 10,000-node chain, recursive calls overflow Python's ~1,000-frame call-stack limit with RecursionError.

Here is how our non-recursive algorithm handles Example 1 (span 102 under 100 at t=45, span 100 root at t=12, span 101 under 100 at t=28):

  1. Allocate nodes: Copy all three dicts into nodes = {102: {...}, 100: {...}, 101: {...}}, giving each copy "children": [].
  2. Sort chronologically: Ordering by startTime yields [span 100 (t=12), span 101 (t=28), span 102 (t=45)].
  3. Wire parents: span 100 has parentId = None, so nodes[100] enters roots. Next, span 101 appends nodes[101] into nodes[100]["children"], and span 102 appends nodes[102] right behind it, yielding [nodes[101], nodes[102]]—already ordered 28, 45!

Complexity

Let n be len(spans).

  • Time: O(n log n). Phase 1 visits each of the n records once, copying its fields and inserting into nodes in O(1) average time (O(n) total). Phase 2 sorts all n records by startTime in O(n log n) comparisons. Phase 3 visits the n sorted records once, doing one O(1) dictionary lookup and one O(1) list .append() per record (O(n) total). Sorting dominates at O(n log n).
  • Space: O(n). We hold n copied node dictionaries, n entries in nodes, and n references in sorted_spans. Because no recursive calls occur, call-stack memory stays O(1) even on a 10,000-level chain.

Edge cases

  • Empty input ([]): Both loops perform zero iterations and return [].
  • Child precedes its parent in spans: Handled cleanly because Phase 1 populates nodes for all records before Phase 3 wires any edge.
  • Child has an earlier startTime than its parent: Because of clock skew (slight clock drift across machines), a child can report a smaller startTime than its parent. Wiring Python object references via parentId works regardless of whether the child or the parent is wired first.
  • parentId equal to 0 or "": Valid identifiers that must attach to span 0 or "", handled properly by checking parent_id is None instead of truthiness.
  • Omitted "parentId" key: span.get("parentId") returns None without raising KeyError, treating the span as a root while preserving its original keys.
  • Multiple independent traces: Multiple spans with parentId is None become separate entries in roots, each heading its own tree.
  • Deep chain of 10,000 spans: Iterative for loops never grow the call stack, finishing in milliseconds without RecursionError.
  • Siblings with equal startTime: Python uses Timsort, a stable sort (a sorting algorithm that preserves the original relative order of tied items), keeping tied siblings in input order.

Common mistakes

  • Writing if not parent_id: instead of if parent_id is None:: In Python, not 0 and not "" evaluate to True, detaching every child of span 0 into a false root.
  • Mutating caller dictionaries in place: Assigning span["children"] = [] directly alters the caller's input list; always shallow-copy via dict(span).
  • Allocating and linking in a single pass: Even after sorting by startTime, clock skew lets a child start earlier than its parent, so a single pass without pre-populating nodes can miss a parent that sits later in sorted_spans.
  • Recursing down the tree: Any recursive walk crashes on 10,000-node linear chains under Python's default recursion limit.
  • Omitting "children": [] on leaves: Every returned dictionary—leaves included—must carry "children".

Alternative approaches

  • Wire in input order, then sort each node's "children" list: Skip the global sort, wire children in input order, and finish with for node in nodes.values(): node["children"].sort(key=_get_start_time). When node i has c_i children, total comparison work sums c_i log c_i, which is bounded by O(n log n) worst-case and drops to O(n) when branching factors are tiny. Sorting once upfront is equally clean and orders roots chronologically as well.

Follow-up questions

  • What happens if corrupted input data introduces a parent-pointer loop, and how can you detect those loops? A cycle (a closed parent chain such as A -> B -> A or self-loop A -> A) contains no None parent, so every node on the loop—plus any subtree attached to it—never enters roots and silently disappears from the returned list. After Phase 3, traverse downward from roots with an explicit stack list to count reachable nodes in O(n) time: whenever reachable_count < len(nodes), at least one parent loop exists. To isolate the exact loop members, follow parentId upward from each unvisited node with a current_chain set to spot the first repeated ID and a global inspected set so every node is walked at most once.
  • How would you adapt the design to assemble trees on the fly as span events trickle in continuously? Persist nodes across arriving events and create lightweight placeholder entries whenever a child references a parentId whose own span has not arrived yet. When a span arrives, populate its placeholder (if present) or allocate a new node, then insert it into its parent's "children" list at its sorted startTime position via binary search (bisect.insort, which halves the search range to locate the insertion index, doing O(c) list shifting across c siblings). Evict completed traces after an inactivity watermark/TTL, promoting or flagging any placeholder parent that never arrived.
  • What are the asymptotic runtime and memory bounds, and how does the runtime behave when inputs arrive nearly ordered by startTime? Runtime is O(n log n) and memory is O(n), with the startTime sort as the sole super-linear step. Because Python's sorted() uses Timsort—which scans for natural ascending/descending runs and merges them—completely ordered inputs finish in O(n) time (n - 1 comparisons), and nearly ordered batches with only a handful of out-of-order stragglers run in O(n log r) time where r is the small count of monotonic runs.

Follow-up questions

Similar questions

More Datadog interview questions

All 18 Datadog questions →