KatInterview

Compute Reporting Metrics in a Company Hierarchy

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphstreedfspost-order

Last 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 identifier
  • manager_id: the id of their direct manager, or None if 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:

  1. is_manager: True if the employee has at least one direct report, False otherwise
  2. direct: the count of employees who report directly to this person
  3. 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 id is unique and appears exactly once
  • Every non-None manager_id refers to a valid employee id in 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.