Highest-Cost Root Job by Subtree Duration
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
A distributed worker cluster records completed tasks as a list of dictionaries jobs. Each dictionary describes a single task execution with the following fields:
id: unique identifier of the task (string or integer)parent_id: identifier of the parent task that enqueued it, orNone(or omitted from the dictionary) when the task is a root (top-level) jobduration_ms: runtime of that individual task in milliseconds
Because tasks can enqueue child tasks across arbitrarily many levels, the log forms a forest of trees rooted at top-level jobs. A top-level job's total cost equals its own duration_ms plus the duration_ms of every descendant task beneath it across all levels.
Implement highest_cost_top_level_job(jobs) to find the top-level job with the largest total cost:
def highest_cost_top_level_job(jobs: List[Dict]) -> Optional[Dict]:
Rules:
- Return a dictionary {"id": <top_level_id>, "total_cost_ms": <total_cost>} for the highest-cost top-level job.
- If jobs contains no top-level jobs (for instance, an empty list), return None. A top-level job whose total cost is 0 is still a valid job and must return {"id": ..., "total_cost_ms": 0}.
- If multiple top-level jobs tie for the maximum total cost, returning any tied winner is valid (keeping the earliest tied top-level job in input order is deterministic).
- Entries in jobs may appear in any order (children may precede parents), 0 and "" are valid task identifiers (only None or an omitted "parent_id" marks a top-level job), and orphaned or cyclic records unreachable from any top-level job belong to no root tree.
Examples
Example 1
Input:
jobs = [
{"id": "sync", "parent_id": None, "duration_ms": 12},
{"id": "fetch", "parent_id": "sync", "duration_ms": 8},
{"id": "parse", "parent_id": "sync", "duration_ms": 6},
{"id": "backup", "parent_id": None, "duration_ms": 30},
]
Output:
{"id": "backup", "total_cost_ms": 30}
Walk-through: Root job "sync" plus its two children "fetch" and "parse" totals 12 + 8 + 6 = 26 ms, whereas standalone root job "backup" runs for 30 ms and wins.
Example 2
Input:
jobs = [
{"id": "export", "duration_ms": 15},
{"id": "compress", "parent_id": "export", "duration_ms": 9},
{"id": "upload", "parent_id": "compress", "duration_ms": 11},
]
Output:
{"id": "export", "total_cost_ms": 35}
Walk-through: "export" omits "parent_id" so it is top-level; summing across "export" (15), its child "compress" (9), and its grandchild "upload" (11) produces 35 ms.
Example 3
Input:
jobs = [
{"id": "audit", "parent_id": None, "duration_ms": 11},
{"id": "notify", "parent_id": "audit", "duration_ms": 7},
{"id": "cleanup", "parent_id": None, "duration_ms": 18},
]
Output:
{"id": "audit", "total_cost_ms": 18}
Walk-through: "audit" (11 + 7 = 18 ms) and "cleanup" (18 ms) tie for the highest total cost; returning the first tied top-level job yields "audit" with 18.
Constraints
0 <= len(jobs) <= 10^50 <= duration_ms <= 10^9(integer)- Task
idvalues are unique hashable values (such as strings or integers, including0or""). - Tree depth can reach
len(jobs)(10^5levels in a single chain).
Step-by-step walkthrough
Understand the job hierarchy and edge rules
Each dictionary in
jobsdescribes one task execution:id: unique identifier for the task,parent_id:idof the parent task that enqueued it, or omitted /Nonewhen this task is a top-level job,duration_ms: milliseconds spent executing that individual task.
Across all records, top-level jobs and their descendants form a forest — a collection of separate trees, one rooted at each top-level job. A top-level job's total cost combines its own
duration_mswith theduration_msof every child, grandchild, and deeper descendant beneath it. We return{"id": <winner_id>, "total_cost_ms": <max_cost>}, orNonewhen no top-level job exists.Four boundary rules deserve special care:
- Omitted key vs.
Nonevs.0: Both an absent"parent_id"key and"parent_id": Nonemark a top-level job (job.get("parent_id") is None). Never writeif not job.get("parent_id"):, because0and""are falsy in Python even though they are valid task IDs! - Ties: Any tied winner is valid; updating only on strict
>deterministically keeps the first top-level job in input order (matching"audit"in Example 3). - Zero-cost jobs vs. no roots: A top-level job with
0total cost must still return{"id": ..., "total_cost_ms": 0}, whereas having zero top-level jobs returnsNone. - Orphans and cycles: A task whose
parent_idis absent fromjobs(an orphan) or that lies on a parent loop (X -> Y -> X, a cycle) has no top-level ancestor, so its runtime belongs to no root tree.
Why climbing upward from every job is too slow
Because each dictionary points to
parent_id, a tempting first pass is: for each task, followparent_idlinks upward until reaching a top-level root, and addduration_msinto that root's accumulator.Watch what happens on a deep chain of
ntasks (0 -> 1 -> 2 -> ... -> n-1):Chain: job 0 (root) <-- job 1 <-- job 2 <-- job 3 <-- ... <-- job (n-1) Upward hops per task: job 0 climbs 0 links job 1 climbs 1 link (1 -> 0) job 2 climbs 2 links (2 -> 1 -> 0) job 3 climbs 3 links (3 -> 2 -> 1 -> 0) ... Total hops = 0 + 1 + 2 + ... + (n - 1) = n * (n - 1) / 2 --> O(n^2)!At
100,000tasks,O(n^2)performs roughly5,000,000,000dictionary lookups — and if two tasks point at each other (X <-> Y), climbing upward spins forever unless extra cycle tracking is added.Key idea: invert parent links once and traverse downward from each root
Instead of climbing upward from every descendant repeatedly, we make one linear pass to build a parent-to-children lookup table
children_by_parent[parent_id] -> [child_job, ...], and then walk downward once starting at each top-level job:Raw parent links (child -> parent): Inverted map `children_by_parent` (parent -> children): sync (12ms, parent: None) "sync": [fetch (8ms), parse (6ms)] fetch ( 8ms, parent: "sync") parse ( 6ms, parent: "sync") Walk down from root "sync": backup (30ms, parent: None) 12 + 8 + 6 = 26ms Walk down from root "backup": 30ms --> Winner!Why is this both linear (
O(n)) and cycle-safe when IDs are unique?- Every task has at most one
parent_id, so it sits in at most onechildren_by_parentlist and is visited at most once across all root traversals combined. - Every node reached downward from a root
Rhas a unique parent chain leading back toR. Any node on a cycle (X <-> Y) or underneath a missing parent (O -> "missing") has no chain back to a root, so downward root walks never visit it and never hang!
- Every task has at most one
Step 1: build the parent-to-children lookup table
Scan
jobsonce and group every non-root task under itsparent_id. Top-level jobs (parent_id is None) are skipped here because they serve as the starting roots in Phase 2:from typing import Any, Dict, List def build_children_map(jobs: List[Dict]) -> Dict[Any, List[Dict]]: """Map each parent_id to the list of job dicts that name it as their parent.""" children_by_parent: Dict[Any, List[Dict]] = {} for job in jobs: parent_id = job.get("parent_id") # Check `is None` explicitly because 0 or "" can be valid parent IDs. if parent_id is None: continue if parent_id not in children_by_parent: children_by_parent[parent_id] = [] children_by_parent[parent_id].append(job) return children_by_parentStep 2: sum each tree iteratively with an explicit stack
Writing
subtree_costrecursively (job["duration_ms"] + sum(subtree_cost(c) ...)) looks compact, yet CPython's default call-stack limit is1000frames — a chain of100,000tasks immediately raisesRecursionError.Instead, we run iterative depth-first search (DFS) with an explicit list
stack = [root_job]: whilestackis non-empty, pop one task, add itsduration_mstototal_cost, and push its direct children ontostack. Because addition is commutative, visit order inside a subtree does not affect the sum!Then in
highest_cost_top_level_job, scanjobsin input order, evaluate every top-level job, and updatebest_jobwheneverbest_job is Noneortotal_cost > best_job["total_cost_ms"]:from typing import Any, Dict, List, Optional def compute_subtree_cost(root_job: Dict, children_by_parent: Dict[Any, List[Dict]]) -> int: """Sum duration_ms across `root_job` and all of its descendants iteratively.""" total_cost = 0 stack = [root_job] while stack: current_job = stack.pop() total_cost += current_job["duration_ms"] for child_job in children_by_parent.get(current_job["id"], []): stack.append(child_job) return total_cost def highest_cost_top_level_job(jobs: List[Dict]) -> Optional[Dict]: children_by_parent = build_children_map(jobs) best_job: Optional[Dict] = None for job in jobs: if job.get("parent_id") is not None: continue total_cost = compute_subtree_cost(job, children_by_parent) if best_job is None or total_cost > best_job["total_cost_ms"]: best_job = {"id": job["id"], "total_cost_ms": total_cost} return best_jobTrace through Example 1
Let's walk
jobs = [sync(12, None), fetch(8, 'sync'), parse(6, 'sync'), backup(30, None)]:1) build_children_map(jobs): children_by_parent = {"sync": [fetch(8), parse(6)]} 2) Evaluate top-level job "sync": stack = [sync] -> pop sync (+12ms), push fetch, parse -> total_cost = 12 stack = [fetch, parse] -> pop parse (+6ms), no children -> total_cost = 18 stack = [fetch] -> pop fetch (+8ms), no children -> total_cost = 26, stack = [] best_job becomes {"id": "sync", "total_cost_ms": 26} 3) Skip "fetch" and "parse" (parent_id is "sync", not None). 4) Evaluate top-level job "backup": stack = [backup] -> pop backup (+30ms), no children -> total_cost = 30, stack = [] 30 > 26 -> best_job becomes {"id": "backup", "total_cost_ms": 30}Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def build_children_map(jobs: List[Dict]) -> Dict[Any, List[Dict]]: """Map each parent_id to the list of job dicts that name it as their parent.""" # children_by_parent: maps parent_id -> list of child job dicts, e.g. {"sync": [job_fetch, job_parse]} children_by_parent: Dict[Any, List[Dict]] = {} for job in jobs: parent_id = job.get("parent_id") # Check `is None` explicitly because 0 or "" can be valid parent IDs. if parent_id is None: continue if parent_id not in children_by_parent: children_by_parent[parent_id] = [] children_by_parent[parent_id].append(job) return children_by_parent def compute_subtree_cost(root_job: Dict, children_by_parent: Dict[Any, List[Dict]]) -> int: """Sum duration_ms across `root_job` and all of its descendants iteratively.""" total_cost = 0 # stack: explicit list of job dicts waiting to be visited; avoids Python's recursion limit stack = [root_job] while stack: current_job = stack.pop() total_cost += current_job["duration_ms"] for child_job in children_by_parent.get(current_job["id"], []): stack.append(child_job) return total_cost def highest_cost_top_level_job(jobs: List[Dict]) -> Optional[Dict]: # Phase 1: Invert parent_id links once so each job's direct children are O(1) to look up. children_by_parent = build_children_map(jobs) # Phase 2: Scan in input order and evaluate every top-level job's full tree cost. # Start `best_job` at None so a 0ms top-level job still counts, while 0 roots returns None. best_job: Optional[Dict] = None for job in jobs: if job.get("parent_id") is not None: continue total_cost = compute_subtree_cost(job, children_by_parent) # Strict `>` keeps the earliest top-level job in input order when total costs tie. if best_job is None or total_cost > best_job["total_cost_ms"]: best_job = {"id": job["id"], "total_cost_ms": total_cost} return best_job✅ Submit now — all tests should pass.
Intuition & how it works
Think of worker tasks like a company org chart: each top-level job (parent_id omitted or None) is a department lead that enqueues child tasks, which in turn enqueue grandchild tasks, forming a forest (a collection of separate trees, one rooted at each top-level job). In the raw input list, every record only points upward to its boss (parent_id), never downward to its direct reports. Rather than forcing every task to climb all the way up its management chain to add milliseconds onto the root's tally, we flip the links once into a lookup dictionary children_by_parent (boss_id -> list of direct child dicts), and then start at each top-level job and walk downward using an explicit stack (a heap-allocated to-do list where we pop one task, add its duration_ms, and push its children until empty — an iterative depth-first search (DFS)).
Why do naive approaches break down? Walking upward from each task re-traverses shared ancestors repeatedly, degrading to O(n^2) time on a deep chain of n tasks and spinning forever if malformed logs contain a cycle (tasks whose parent_id pointers loop back on themselves, such as X -> Y -> X). Meanwhile, coding the downward tree sum with function recursion overflows Python's ~1,000-frame call stack (the fixed-depth memory buffer tracking active function calls) and crashes with RecursionError on deep pipelines.
Let's trace Example 2 (export: 15ms -> compress: 9ms -> upload: 11ms) through our two-phase pipeline:
Phase 1 — Invert parent links into `children_by_parent`:
"export" -> [compress (9ms)]
"compress" -> [upload (11ms)]
Phase 2 — Iterative stack walk starting from top-level "export":
stack = [export] -> pop export (+15ms), push compress -> total = 15
stack = [compress] -> pop compress (+9ms), push upload -> total = 24
stack = [upload] -> pop upload (+11ms), no children -> total = 35
stack = [] -> return {"id": "export", "total_cost_ms": 35}
Complexity
Let n be len(jobs).
- Time:
O(n)average. Buildingchildren_by_parentvisits allntasks once usingO(1)average dictionary lookups and list appends; across all root traversals combined, each task is pushed onto and popped fromstackat most once (only when its single parent is popped), doingO(1)arithmetic per task. - Space:
O(n).children_by_parentholds at mostntask references across all child lists, andstackholds at mostntask references at any instant.
Edge cases
- Empty list or zero top-level jobs (e.g., every record lies on a cycle):
best_jobstaysNoneandNoneis returned. - Top-level job with
0total cost: Startingbest_job = None(rather thanbest_cost = 0) ensures{"id": ..., "total_cost_ms": 0}is returned as a valid winner. - Omitted
"parent_id"key vs."parent_id": None:job.get("parent_id")evaluates toNonein both cases, treating both as top-level (Example 2). - Falsy IDs (
0or""): Testingparent_id is None(rather thanif not parent_id) preserves0and""as legitimate parent IDs so children of task0are not mistaken for roots. - Children listed ahead of parents: Indexing all records into
children_by_parentbefore summing subtrees makes input ordering irrelevant. - Tied maximum totals (Example 3): Strict
>(total_cost > best_job["total_cost_ms"]) preserves the earliest top-level job in input order. - Deep chains (
100,000+levels): Processed cleanly in linear time and heap memory without touching Python's recursion limit. - Orphans and cycles (with unique IDs): An orphan (whose
parent_idis missing fromjobs) or a task on a parent cycle has no downward path from any root, so root-downward traversal skips it automatically without hanging.
Common mistakes
- Recursive DFS (
def dfs(job): ...): Readable on shallow examples, but crashes withRecursionErroronce chain depth passes ~1,000 levels. - Truthiness checks (
if not job.get("parent_id"):): Wrongly treats"parent_id": 0as "no parent," promoting children of task0into separate roots. - Tracking
max_cost = 0and returningNonewhenmax_cost == 0: Fails whenever the winning top-level job took0ms. - Summing only direct children: Drops grandchildren and deeper levels.
- Uncached upward parent walks: Degrades to
O(n^2)on skewed chains and loops infinitely on cycles unless guarded.
Alternative approaches
- Upward root-finding with path memoization: Walk
parent_idlinks upward from each task to locate its top-level ancestor (orNoneif orphaned/cyclic), cachingroot_of[job_id]for every node along the chain so no link is walked twice. Runs inO(n)time without child lists, though cycle safety requires an "active path" set per walk. - Bottom-up post-order accumulation: Push reachable tasks in top-down order from roots and iterate that list in reverse, adding
subtotal[child]intosubtotal[parent]. AlsoO(n)time and handy if interior node subtree totals are needed too.
Follow-up questions
- Why can recursive tree traversal crash on deep job chains in Python, and how do you eliminate that risk? Every nested Python function call pushes a frame onto CPython's fixed-depth call stack, which defaults to
1,000frames (RecursionError) and cannot safely be raised indefinitely without risking an OS C-stack segfault. Replacing function recursion with an explicit heap-allocatedstacklist (iterative DFS) orcollections.dequequeue (iterative breadth-first search), ascompute_subtree_costdoes, removes recursion-depth limits completely while keepingO(n)time and memory. - What input-validation checks would you add before aggregating untrusted job logs in production? Run a single
O(n)schema-and-integrity pass verifying that: (1) every entry is adictwith a non-null hashableid, (2) allidvalues are unique, (3)duration_msis a finite non-negativeintorfloat(explicitly rejectingbool, sinceisinstance(True, int)isTruein Python!), and (4) policy for unknownparent_idvalues (warn/quarantine vs. raise) is enforced. Enforcing unique IDs is critical because duplicate records like{"id": "sync", "parent_id": None}alongside{"id": "sync", "parent_id": "sync"}would place"sync"inside its own child list and loop even a downward traversal unless avisitedset is maintained. - How can you detect and surface parent-pointer cycles in linear time? Follow
parent_idlinks using three-color marking (assigning each task0 = unvisited,1 = on current walk, or2 = verified acyclic): stepping onto a node in state1immediately pinpoints the exact cycle, whereas hittingNone, a missing parent, or a state-2node lets you mark the entire walked chain2so every task is inspected at most twice (O(n)total). - How would you process multi-gigabyte job logs or track root job costs in a live distributed worker system? For huge offline files, switch from a monolithic JSON array to JSON Lines (NDJSON) (one JSON record per line) or a streaming parser (
ijson) and store only compact(parent_id, duration_ms)entries or an external key-value store instead of full Python dictionaries. In a live worker system, propagateroot_job_idonto each child payload when it is enqueued (child.root_job_id = parent.root_job_id or parent.id); then computing every top-level job's total cost reduces to an indexedGROUP BY root_job_idquery or an atomic counter increment as tasks complete.
Follow-up questions
- Why can recursive tree traversal crash on deep job chains in Python, and how do you eliminate that risk?
- What input-validation checks would you add before aggregating untrusted job logs in production?
- How can you detect and surface parent-pointer cycles in linear time?
- How would you process multi-gigabyte job logs or track root job costs in a live distributed worker system?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array