The 'orphan root' part is where I lost a minute.
First, build a hash map from span_id to span for O(1) lookups, then iterate through the spans to assign each to its parent's children list or to the roots list if it's a root. Finally, recursively sort each node's children by start_time and return the roots.
Pro tip: Mention that you can avoid recursion depth issues by using an iterative post-order traversal or by sorting children during the initial pass, and highlight that this approach handles orphaned spans gracefully.
Confirm that spans with missing parents are roots, that children are sorted by start_time, and discuss handling of cycles or duplicate IDs.
Create a dictionary mapping span_id to span object for O(1) access, and initialize an empty children list for each span.
Iterate through all spans: if parent_id is None or not in the map, add to roots; otherwise, append to the parent's children list.
For each root, perform a depth-first traversal to sort children by start_time at every level, ensuring the entire tree is ordered.
Return the list of root spans, each with its nested children field representing the sorted subtree.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.