Costliest Root Task in a Task Forest
Trees & GraphsAuto-graded · 17 test casesLast updated
Sum durations over each root's subtree in a parent-linked record list and return the root with the largest total, testing tree aggregation and iterative traversal.
Costliest Root Task in a Task Forest
A scheduler logs its tasks as a flat list of records. Each record is a dictionary with these keys:
id: a unique identifier for the task.parent_id: theidof the task that launched this one. For a root task, this key is eitherNoneor absent altogether.duration_ms: a number giving how long this task ran, in milliseconds.
Tasks can launch other tasks, which can launch still more, so the records form a forest of trees. The total cost of a root task is its own duration_ms plus the duration_ms of every task below it, at any depth.
Write a function that finds the root task with the greatest total cost and returns it together with that cost.
Output
- Return a dictionary
{"id": <root id>, "total_cost_ms": <total cost>}. - If several roots share the maximum total cost, return the one that appears earliest in the input list.
- If the list is empty, or no record is a root, return
None.
Rules
- A record is a root when
parent_idis missing or equal toNone. Other falsy values, such as0or"", are real parent ids and do not make a task a root. - Only descendants of a root count toward that root's total. A task whose
parent_idpoints to an id that does not exist, or one that sits in a parent cycle, is not reachable from any root and is ignored. - Chains can be very deep, so avoid relying on Python's default recursion limit.
Constraints
0 <= len(job_records) <= 10^5- All
idvalues are unique and hashable (strings or integers). - Every record has a numeric
duration_ms; totals are compared as plain numbers. - Records may appear in any order; a child may be listed before its parent.
- The depth of a tree can reach
10^5.
Examples
Example 1
Input: costliest_root_job([{'id': 'A', 'parent_id': None, 'duration_ms': 5}, {'id': 'B', 'parent_id': 'A', 'duration_ms': 1}, {'id': 'C', 'parent_id': 'A', 'duration_ms': 3}, {'id': 'D', 'parent_id': None, 'duration_ms': 20}])
Output: {'id': 'D', 'total_cost_ms': 20}
Example 2
Input: costliest_root_job([{'id': 'root', 'duration_ms': 10}, {'id': 'child', 'parent_id': 'root', 'duration_ms': 2}, {'id': 'grandchild', 'parent_id': 'child', 'duration_ms': 4}])
Output: {'id': 'root', 'total_cost_ms': 16}
Example 3
Input: costliest_root_job([{'id': 'A', 'parent_id': None, 'duration_ms': 5}, {'id': 'B', 'parent_id': None, 'duration_ms': 5}])
Output: {'id': 'A', 'total_cost_ms': 5}
Hints
Hint 1
Each record only points upward to its parent, but summing a tree means walking downward. Build a map from each parent id to the list of its child ids.
Hint 2
Only the totals of the roots matter. For each root, a simple traversal that adds up every reachable duration is enough, with no per-node subtree sums needed.
Hint 3
Use an explicit stack instead of recursion to survive very deep chains. Start with the first root as the best, then replace it only on a strictly greater total, so ties keep the earliest root.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The records only point from child to parent, but a root's cost requires visiting everything below it. So the solution works in two steps.
- Index the records in one pass.
- Map each id to its duration.
- Map each parent id to the list of its children's ids.
- Collect the roots, in input order, as the records whose
parent_idis missing orNone. The check must beis None, not a truthiness test, so ids like0or""are not mistaken for "no parent".
- Total each root's tree. For every root, run an iterative post-order traversal with an explicit stack. Each node's total is its own duration plus the totals of its children. Then scan the roots in input order, starting with the first as the best and replacing it only on a strictly greater total, so ties keep the earliest root.
If there are no records or no roots, return None.
Why it is correct
- Every task has at most one parent, so it belongs to at most one tree. Each reachable task is therefore counted exactly once in its root's total.
- The set of tasks reachable from a root through child links is exactly its descendants, which matches the definition of total cost.
- Orphans (parent id not present) and tasks in parent cycles can never be reached from a root, because following their parent links never ends at a
Noneparent. They are skipped automatically, as the rules require, and the traversal cannot loop forever. - Initializing the best root with the first root, rather than a sentinel such as
-1, keeps the result correct for any numeric totals, and the strict comparison yields the required tie-break. - The explicit stack avoids recursion limits on chains up to
10^5deep.
Complexity
- Time: O(n). The indexing pass and the traversals each touch every record and edge a constant number of times.
- Space: O(n) for the duration map, the children lists, the totals and the stack.
Reference solution
from typing import List, Dict, Optional
def costliest_root_job(job_records: List[Dict]) -> Optional[Dict]:
if not job_records:
return None
durations = {}
children = {}
roots = []
for rec in job_records:
task_id = rec["id"]
durations[task_id] = rec["duration_ms"]
parent = rec.get("parent_id")
if parent is None:
roots.append(task_id)
else:
children.setdefault(parent, []).append(task_id)
if not roots:
return None
totals = {}
for root in roots:
stack = [(root, False)]
while stack:
node, expanded = stack.pop()
if not expanded:
stack.append((node, True))
for child in children.get(node, []):
stack.append((child, False))
else:
totals[node] = durations[node] + sum(
totals[child] for child in children.get(node, [])
)
best_id = roots[0]
for root in roots[1:]:
if totals[root] > totals[best_id]:
best_id = root
return {"id": best_id, "total_cost_ms": totals[best_id]}