Compute Reporting Metrics in a Company Hierarchy
Trees & GraphsAuto-graded · 18 test casesLast updated
Tests tree construction from parent pointers and post-order traversal to aggregate counts across nested organizational levels.
You are given a list of employees in a company. Each employee is represented as a dictionary with two keys:
id: a unique integer identifiermanager_id: theidof their direct manager, orNoneif they have no manager
The company structure may contain multiple independent hierarchies (a forest of trees).
Your task is to compute reporting metrics for every employee:
- is_manager:
Trueif the employee has at least one direct report,Falseotherwise - direct: the count of employees who report directly to this person
- total: the count of all employees in their reporting chain (direct reports plus everyone below them, recursively)
Return a dictionary mapping each employee id to a dictionary containing these three metrics.
Constraints
1 <= len(employees) <= 100,000- Every
idis unique and appears exactly once - Every non-
Nonemanager_idrefers to a valid employeeidin the input - The structure is guaranteed to be a valid forest (no cycles)
- Employee IDs are positive integers
Examples
Example 1
Input: compute_org_metrics([{'id': 1, 'manager_id': None}, {'id': 2, 'manager_id': 1}, {'id': 3, 'manager_id': 2}, {'id': 4, 'manager_id': 1}])
Output: {'1': {'is_manager': True, 'direct': 2, 'total': 3}, '2': {'is_manager': True, 'direct': 1, 'total': 1}, '3': {'is_manager': False, 'direct': 0, 'total': 0}, '4': {'is_manager': False, 'direct': 0, 'total': 0}}
Example 2
Input: compute_org_metrics([{'id': 10, 'manager_id': None}])
Output: {'10': {'is_manager': False, 'direct': 0, 'total': 0}}
Example 3
Input: compute_org_metrics([{'id': 1, 'manager_id': None}, {'id': 2, 'manager_id': 1}, {'id': 3, 'manager_id': 1}, {'id': 4, 'manager_id': 3}, {'id': 5, 'manager_id': None}])
Output: {'1': {'is_manager': True, 'direct': 2, 'total': 3}, '2': {'is_manager': False, 'direct': 0, 'total': 0}, '3': {'is_manager': True, 'direct': 1, 'total': 1}, '4': {'is_manager': False, 'direct': 0, 'total': 0}, '5': {'is_manager': False, 'direct': 0, 'total': 0}}
Hints
Hint 1
The input gives you parent pointers, but the metrics you need depend on information below each node. Build a children adjacency list by inverting the manager relationships.
Hint 2
Subtree sizes require knowing all children's sizes first—this is a post-order traversal starting from the roots (employees with no manager).
Hint 3
For very deep hierarchies, an iterative stack-based traversal avoids hitting Python's recursion limit. Push each node twice: once to explore children, once to compute totals after children finish.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The input provides upward pointers (each employee points to their manager), but the metrics we need require downward information (how many people report to each employee). The solution has three phases:
1. Invert the edges
Build a children adjacency list by iterating through all employees and recording each person under their manager. Initialize an empty list for every employee ID so that individual contributors are represented with no children.
2. Count direct reports
Once the adjacency list is built, the direct report count is simply the length of each employee's children list. An employee is a manager if this count is positive.
3. Compute total descendants with post-order traversal
The total descendant count follows a recursive formula:
total(e) = sum over each child c of: (1 + total(c))
The 1 counts the child themselves, and total(c) counts everyone below that child. This requires knowing all children's totals before computing the parent's total—a classic post-order traversal.
Since the structure may be a forest, we start the traversal from every root (employees with manager_id = None). To handle very deep hierarchies without hitting Python's recursion limit, we use an explicit stack-based iterative approach:
- Push each node twice: first with a
processed=Falseflag, then withprocessed=True - On the first visit, push the node back marked as processed, then push all its children
- Because of stack (LIFO) ordering, all children complete before the node's second visit
- On the second visit, all children's totals are known, so compute this node's total
Why It Works
- Every employee is reachable from exactly one root, so seeding the stack with all roots visits everyone exactly once
- The two-phase stack entry ensures children finish before parents: when we pop
(emp_id, True), every descendant has already been processed - The formula counts each person in the subtree exactly once by structural induction on tree height
Complexity
- Time: O(N) where N is the number of employees. Building the adjacency list scans all employees once. The traversal visits each employee twice (two stack entries), and the sum over children touches each parent-child edge once. A forest has fewer than N edges.
- Space: O(N) for the adjacency lists, the descendant counts map, the output dictionary, and the traversal stack.
Solution Code
from typing import Dict, List
def compute_org_metrics(employees: List[Dict]) -> Dict[int, Dict]:
# Build adjacency list: map each employee to their list of direct reports
direct_reports = {emp['id']: [] for emp in employees}
for emp in employees:
if emp['manager_id'] is not None:
direct_reports[emp['manager_id']].append(emp['id'])
# Post-order traversal to compute total descendant counts
descendant_counts = {}
stack = [(emp['id'], False) for emp in employees if emp['manager_id'] is None]
while stack:
emp_id, processed = stack.pop()
if not processed:
# First visit: mark for reprocessing and queue children
stack.append((emp_id, True))
for report_id in direct_reports[emp_id]:
stack.append((report_id, False))
else:
# Second visit: all children done, compute this node's total
descendant_counts[emp_id] = sum(
1 + descendant_counts[report_id]
for report_id in direct_reports[emp_id]
)
# Build final result
return {
emp_id: {
'is_manager': len(direct_reports[emp_id]) > 0,
'direct': len(direct_reports[emp_id]),
'total': descendant_counts[emp_id]
}
for emp_id in direct_reports
}