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, or None (or omitted from the dictionary) when the task is a root (top-level) job
  • duration_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^5
  • 0 <= duration_ms <= 10^9 (integer)
  • Task id values are unique hashable values (such as strings or integers, including 0 or "").
  • Tree depth can reach len(jobs) (10^5 levels in a single chain).

Step-by-step walkthrough

  1. Understand the job hierarchy and edge rules

    Each dictionary in jobs describes one task execution:

    • id: unique identifier for the task,
    • parent_id: id of the parent task that enqueued it, or omitted / None when 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_ms with the duration_ms of every child, grandchild, and deeper descendant beneath it. We return {"id": <winner_id>, "total_cost_ms": <max_cost>}, or None when no top-level job exists.

    Four boundary rules deserve special care:

    • Omitted key vs. None vs. 0: Both an absent "parent_id" key and "parent_id": None mark a top-level job (job.get("parent_id") is None). Never write if not job.get("parent_id"):, because 0 and "" 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 0 total cost must still return {"id": ..., "total_cost_ms": 0}, whereas having zero top-level jobs returns None.
    • Orphans and cycles: A task whose parent_id is absent from jobs (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.
  2. Why climbing upward from every job is too slow

    Because each dictionary points to parent_id, a tempting first pass is: for each task, follow parent_id links upward until reaching a top-level root, and add duration_ms into that root's accumulator.

    Watch what happens on a deep chain of n tasks (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,000 tasks, O(n^2) performs roughly 5,000,000,000 dictionary lookups — and if two tasks point at each other (X <-> Y), climbing upward spins forever unless extra cycle tracking is added.

  3. 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?

    1. Every task has at most one parent_id, so it sits in at most one children_by_parent list and is visited at most once across all root traversals combined.
    2. Every node reached downward from a root R has a unique parent chain leading back to R. 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!
  4. Step 1: build the parent-to-children lookup table

    Scan jobs once and group every non-root task under its parent_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_parent
    
  5. Step 2: sum each tree iteratively with an explicit stack

    Writing subtree_cost recursively (job["duration_ms"] + sum(subtree_cost(c) ...)) looks compact, yet CPython's default call-stack limit is 1000 frames — a chain of 100,000 tasks immediately raises RecursionError.

    Instead, we run iterative depth-first search (DFS) with an explicit list stack = [root_job]: while stack is non-empty, pop one task, add its duration_ms to total_cost, and push its direct children onto stack. Because addition is commutative, visit order inside a subtree does not affect the sum!

    Then in highest_cost_top_level_job, scan jobs in input order, evaluate every top-level job, and update best_job whenever best_job is None or total_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_job
    
  6. Trace 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}
    
  7. 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. Building children_by_parent visits all n tasks once using O(1) average dictionary lookups and list appends; across all root traversals combined, each task is pushed onto and popped from stack at most once (only when its single parent is popped), doing O(1) arithmetic per task.
  • Space: O(n). children_by_parent holds at most n task references across all child lists, and stack holds at most n task references at any instant.

Edge cases

  • Empty list or zero top-level jobs (e.g., every record lies on a cycle): best_job stays None and None is returned.
  • Top-level job with 0 total cost: Starting best_job = None (rather than best_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 to None in both cases, treating both as top-level (Example 2).
  • Falsy IDs (0 or ""): Testing parent_id is None (rather than if not parent_id) preserves 0 and "" as legitimate parent IDs so children of task 0 are not mistaken for roots.
  • Children listed ahead of parents: Indexing all records into children_by_parent before 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_id is missing from jobs) 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 with RecursionError once chain depth passes ~1,000 levels.
  • Truthiness checks (if not job.get("parent_id"):): Wrongly treats "parent_id": 0 as "no parent," promoting children of task 0 into separate roots.
  • Tracking max_cost = 0 and returning None when max_cost == 0: Fails whenever the winning top-level job took 0 ms.
  • 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_id links upward from each task to locate its top-level ancestor (or None if orphaned/cyclic), caching root_of[job_id] for every node along the chain so no link is walked twice. Runs in O(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] into subtotal[parent]. Also O(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,000 frames (RecursionError) and cannot safely be raised indefinitely without risking an OS C-stack segfault. Replacing function recursion with an explicit heap-allocated stack list (iterative DFS) or collections.deque queue (iterative breadth-first search), as compute_subtree_cost does, removes recursion-depth limits completely while keeping O(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 a dict with a non-null hashable id, (2) all id values are unique, (3) duration_ms is a finite non-negative int or float (explicitly rejecting bool, since isinstance(True, int) is True in Python!), and (4) policy for unknown parent_id values (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 a visited set is maintained.
  • How can you detect and surface parent-pointer cycles in linear time? Follow parent_id links using three-color marking (assigning each task 0 = unvisited, 1 = on current walk, or 2 = verified acyclic): stepping onto a node in state 1 immediately pinpoints the exact cycle, whereas hitting None, a missing parent, or a state-2 node lets you mark the entire walked chain 2 so 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, propagate root_job_id onto 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 indexed GROUP BY root_job_id query or an atomic counter increment as tasks complete.

Follow-up questions

Similar questions

More Collegevine interview questions

All 1 Collegevine questions →