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"(intorstr): unique identifier for this call record (note that0and""are valid identifiers)."parentId"(int,str, orNone, optional): identifier of the enclosing caller span. When"parentId"isNone—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:
- 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). - 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). - Do not mutate the dictionaries inside the caller's
spanslist.
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"inspansis unique (intorstr). - Every non-
None"parentId"matches the"spanId"of another entry inspans, 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
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 optionalparentIdnaming the caller span, and an integerstartTime. Because hosts flush batches independently, records arrive shuffled: child calls routinely appear inspansahead 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
parentIdisNone(or omitted completely). - Every output node preserves all original keys of its span plus
"children": [...]([]on leaves). - Every
"children"list is ordered by ascendingstartTime.
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
startTimetoo. - Tied
startTimevalues: Python's built-insorted()is stable, so siblings with identicalstartTimepreserve their relative input order.
- A root is any record whose
Why a naive top-down search hits two walls
A tempting first idea is to locate every root record, scan the entire
spanslist to gather records whoseparentIdmatches that root'sspanId, sort those children bystartTime, and recurse downward.At
n = 10,000spans, that top-down approach breaks in two ways:- Quadratic runtime (
O(n^2)): Scanning allnrecords for each of thennodes performs10,000 * 10,000 = 100,000,000checks. - Call-stack overflow: A 10,000-span chain
0 -> 1 -> 2 -> ... -> 9999recurses 10,000 levels deep, exceeding Python's ~1,000-frame recursion limit withRecursionError.
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.
- Quadratic runtime (
Key idea: index by `spanId` first, then link in `startTime` order
We can wire the entire forest using flat loops and zero recursion:
- Allocate node copies upfront (
O(n)): Copy every record into a dictionarynodes[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. - Sort records once by
startTime(O(n log n)): Build a chronologically ordered listsorted_spans. - Wire each node to its parent (
O(n)): Sweepsorted_spansfrom smalleststartTimeto largest, fetchnodes[parent_id]inO(1)time, and appendnodetoparent_node["children"](or torootswhenparent_id is None).
Why does one global sort order every
"children"list at every tree depth? Because we visit spans in non-decreasingstartTimeorder, each.append(node)adds a child whosestartTimeis 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"]intonodes["gateway"]["children"]automatically carries along any nested descendants attached tonodes["auth"], even when clock skew causes a child to have an earlierstartTimethan its parent.- Allocate node copies upfront (
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_timekeeps 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 nodesPhase 2 & 3: sort chronologically and wire parents
Watch out for two subtle Python traps when reading
"parentId":- Read with
span.get("parentId")rather thanspan["parentId"]: Because"parentId"is optional on roots, a root dictionary may omit the key entirely;.get("parentId")returnsNonecleanly. - Check
parent_id is None, neverif not parent_id:: Both0and""are falsy in Python! Writingif not parent_id:detaches children of span0and turns them into bogus roots.
We also include
parent_id not in nodesas a defensive fallback so an incomplete trace with a missing parent never raisesKeyError.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- Read with
Trace Example 2 (three-level string IDs)
Let's walk through Example 2 where children and grandchildren precede
"gateway"inspans: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.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):
- Allocate nodes: Copy all three dicts into
nodes = {102: {...}, 100: {...}, 101: {...}}, giving each copy"children": []. - Sort chronologically: Ordering by
startTimeyields[span 100 (t=12), span 101 (t=28), span 102 (t=45)]. - Wire parents:
span 100hasparentId = None, sonodes[100]entersroots. Next,span 101appendsnodes[101]intonodes[100]["children"], andspan 102appendsnodes[102]right behind it, yielding[nodes[101], nodes[102]]—already ordered28, 45!
Complexity
Let n be len(spans).
- Time:
O(n log n). Phase 1 visits each of thenrecords once, copying its fields and inserting intonodesinO(1)average time (O(n)total). Phase 2 sorts allnrecords bystartTimeinO(n log n)comparisons. Phase 3 visits thensorted records once, doing oneO(1)dictionary lookup and oneO(1)list.append()per record (O(n)total). Sorting dominates atO(n log n). - Space:
O(n). We holdncopied node dictionaries,nentries innodes, andnreferences insorted_spans. Because no recursive calls occur, call-stack memory staysO(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 populatesnodesfor all records before Phase 3 wires any edge. - Child has an earlier
startTimethan its parent: Because of clock skew (slight clock drift across machines), a child can report a smallerstartTimethan its parent. Wiring Python object references viaparentIdworks regardless of whether the child or the parent is wired first. parentIdequal to0or"": Valid identifiers that must attach to span0or"", handled properly by checkingparent_id is Noneinstead of truthiness.- Omitted
"parentId"key:span.get("parentId")returnsNonewithout raisingKeyError, treating the span as a root while preserving its original keys. - Multiple independent traces: Multiple spans with
parentId is Nonebecome separate entries inroots, each heading its own tree. - Deep chain of 10,000 spans: Iterative
forloops never grow the call stack, finishing in milliseconds withoutRecursionError. - 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 ofif parent_id is None:: In Python,not 0andnot ""evaluate toTrue, detaching every child of span0into a false root. - Mutating caller dictionaries in place: Assigning
span["children"] = []directly alters the caller's input list; always shallow-copy viadict(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-populatingnodescan miss a parent that sits later insorted_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 withfor node in nodes.values(): node["children"].sort(key=_get_start_time). When nodeihasc_ichildren, total comparison work sumsc_i log c_i, which is bounded byO(n log n)worst-case and drops toO(n)when branching factors are tiny. Sorting once upfront is equally clean and ordersrootschronologically 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 -> Aor self-loopA -> A) contains noNoneparent, so every node on the loop—plus any subtree attached to it—never entersrootsand silently disappears from the returned list. After Phase 3, traverse downward fromrootswith an explicit stack list to count reachable nodes inO(n)time: wheneverreachable_count < len(nodes), at least one parent loop exists. To isolate the exact loop members, followparentIdupward from each unvisited node with acurrent_chainset to spot the first repeated ID and a globalinspectedset 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
nodesacross arriving events and create lightweight placeholder entries whenever a child references aparentIdwhose 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 sortedstartTimeposition via binary search (bisect.insort, which halves the search range to locate the insertion index, doingO(c)list shifting acrosscsiblings). 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 isO(n log n)and memory isO(n), with thestartTimesort as the sole super-linear step. Because Python'ssorted()uses Timsort—which scans for natural ascending/descending runs and merges them—completely ordered inputs finish inO(n)time (n - 1comparisons), and nearly ordered batches with only a handful of out-of-order stragglers run inO(n log r)time whereris the small count of monotonic runs.
Follow-up questions
- What happens if corrupted input data introduces a parent-pointer loop, and how can you detect those loops?
- How would you adapt the design to assemble trees on the fly as span events trickle in continuously?
- What are the asymptotic runtime and memory bounds, and how does the runtime behave when inputs arrive nearly ordered by `startTime`?
Similar questions
- Windowed Metric Sums Filtered by Tag
- Asynchronous Warehouse Query Client
- Thread-Safe Buffered File Writer
- In-Memory Indexed Log Store and Range Queries
- Prefix Match String Filter
- Chunked Buffered Byte Writer
More Datadog interview questions
- Subtree Deletion Using Restricted Filesystem Primitives Medium
- Asynchronous Warehouse Query Client Medium
- Grouped-Query Attention Forward Pass Hard Pro
- Online Keyword Query Matching Over Log Streams Medium Pro
- Windowed Metric Sums Filtered by Tag Medium Pro
- End-to-End Technical Project Walkthrough Medium Pro
- Improving Brevity After Communication Feedback Medium Pro
- Autonomous LLM Coding Agent for Issue-to-PR Resolution Medium Pro
- Production Image Object Detection Service Hard Pro
- Real-Time Log and Query Stream Matcher Hard Pro