Employee Hierarchy: Counting Trees, Level Traversal, and Ancestor Search
Trees & GraphsModel answerLast updated
Build a management structure from employee records, then count independent hierarchies, display staff by organizational depth, and locate shared supervisors.
You receive employee data as a collection of (id, title, reports_to) records. The reports_to field contains the employee ID of that person's direct supervisor, or None for top-level executives who report to no one. Your task is to implement three functions operating on this data structure.
Consider this dataset throughout:
employees = [
(4, "Engineer", 2),
(1, "CEO", None),
(8, "Designer", 7),
(2, "VP Engineering", 1),
(6, "Account Executive", 3),
(3, "VP Sales", 1),
(5, "Engineer", 2),
(7, "Founder", None),
]
Assumptions
- Each ID appears exactly once in the input
- Job titles may repeat and serve only as labels
- Records appear in arbitrary order—a supervisor may be listed after their direct reports
- You may assume the data is well-formed: all non-None
reports_tovalues reference valid employee IDs, and no circular reporting relationships exist
Challenge 1: Count Independent Hierarchies
Determine how many separate organizational hierarchies exist. A hierarchy consists of one top-level executive (with reports_to = None) plus everyone who reports through that chain of command. The example data contains 2 hierarchies.
Your implementation should:
- Run in O(n) time where n is the number of employees
- Handle an empty employee list correctly
- Make no assumptions about input ordering
Challenge 2: Display by Organizational Depth
Output all employees grouped by their distance from a top-level executive. Top executives appear on the first line, their direct reports on the second, and so on. For the example, valid output includes:
1 (CEO), 7 (Founder)
2 (VP Engineering), 3 (VP Sales), 8 (Designer)
4 (Engineer), 5 (Engineer), 6 (Account Executive)
Requirements:
- Employees at the same depth across different hierarchies may share a line
- Within each line, use a consistent ordering (by ID, by first appearance, or grouped by supervisor—your choice, but be explicit)
- Achieve O(n) time and space complexity
Challenge 3: Locate Shared Supervisor
Given two employee IDs, find the most immediate person both report to. This is the first employee who appears in both upward reporting chains. Examples:
- Employees
4and5→2 - Employees
4and6→1 - Employees
4and8→ no shared supervisor (different hierarchies)
Clarifications needed:
- If one employee is the direct or indirect supervisor of the other, should the answer be that employee or their own manager?
- What value indicates "no shared supervisor" for employees in different hierarchies?
- How should invalid employee IDs be handled?
Your solution should:
- Process each query in O(h) time where h is the hierarchy depth
- Handle edge cases: same employee ID twice, non-existent IDs, employees in different trees
Hints
Hint 1
Build a dictionary mapping each employee ID to their manager ID, and another mapping each manager to their list of direct reports—reuse these for all three parts.
Hint 2
For counting hierarchies, identify all employees with reports_to = None; each represents one independent tree.
Hint 3
For level-order output, use breadth-first search starting from all top-level executives simultaneously, or process each hierarchy separately.
Hint 4
To find a shared supervisor, collect all ancestors of one employee into a set, then walk up from the second employee until you find a match.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
All three challenges operate on the same graph structure: a forest of trees where edges point from employee to manager. Building two indexes up front enables efficient solutions for each part.
Data Structure Setup
First, create two dictionaries:
manager_map: maps employee ID → manager ID (or None for top-level)reports_map: maps manager ID → list of direct report IDs
def build_indexes(employees):
manager_map = {}
reports_map = {}
for emp_id, title, reports_to in employees:
manager_map[emp_id] = reports_to
if reports_to not in reports_map:
reports_map[reports_to] = []
reports_map[reports_to].append(emp_id)
return manager_map, reports_map
Building these indexes takes O(n) time and space, where n is the employee count.
Challenge 1: Counting Hierarchies
Each hierarchy is rooted at an employee with reports_to = None. Simply count how many such entries exist:
def count_orgs(employees):
return sum(1 for _, _, reports_to in employees if reports_to is None)
Time: O(n), Space: O(1).
Edge case: An empty list returns 0.
Challenge 2: Level-Order Display
Use breadth-first search to visit employees by depth. Start with all top-level executives in the queue, then process level by level:
def print_by_level(employees):
manager_map, reports_map = build_indexes(employees)
# Find all roots (employees with no manager)
roots = [emp_id for emp_id in manager_map if manager_map[emp_id] is None]
if not roots:
return
# Get title lookup for formatting
id_to_title = {emp_id: title for emp_id, title, _ in employees}
queue = roots
while queue:
# Process entire current level
level_output = []
next_queue = []
for emp_id in sorted(queue): # Sort for deterministic output
level_output.append(f"{emp_id} ({id_to_title[emp_id]})")
# Add all direct reports to next level
if emp_id in reports_map:
next_queue.extend(reports_map[emp_id])
print(", ".join(level_output))
queue = next_queue
Time: O(n log n) due to sorting each level; without sorting, O(n). Space: O(n) for the queue.
Design choice: I sort by ID within each level for reproducibility. Alternatives include grouping by manager or preserving input order.
Challenge 3: Finding Shared Supervisor
Walk upward from one employee to collect all ancestors, then walk up from the second employee until hitting a match:
def find_common_manager(emp_id_1, emp_id_2, manager_map):
# Handle invalid IDs
if emp_id_1 not in manager_map or emp_id_2 not in manager_map:
return None
# Same employee
if emp_id_1 == emp_id_2:
return manager_map[emp_id_1] # Their own manager
# Collect all ancestors of first employee
ancestors = set()
current = emp_id_1
while current is not None:
ancestors.add(current)
current = manager_map.get(current)
# Walk up from second employee until finding a match
current = emp_id_2
while current is not None:
if current in ancestors:
return current
current = manager_map.get(current)
return None # Different hierarchies
Time: O(h) per query where h is tree height. Space: O(h) for the ancestor set.
Key decision: When one employee manages the other, I return the higher employee (the manager). If emp_id_1 == emp_id_2, I return their direct manager. Both are defensible; clarify with your interviewer.
Complete Implementation
def count_orgs(employees):
return sum(1 for _, _, reports_to in employees if reports_to is None)
def print_by_level(employees):
manager_map, reports_map = {}, {}
id_to_title = {}
for emp_id, title, reports_to in employees:
manager_map[emp_id] = reports_to
id_to_title[emp_id] = title
if reports_to not in reports_map:
reports_map[reports_to] = []
reports_map[reports_to].append(emp_id)
roots = [emp_id for emp_id in manager_map if manager_map[emp_id] is None]
queue = roots
while queue:
level_output = [f"{emp_id} ({id_to_title[emp_id]})"
for emp_id in sorted(queue)]
print(", ".join(level_output))
next_queue = []
for emp_id in queue:
if emp_id in reports_map:
next_queue.extend(reports_map[emp_id])
queue = next_queue
def find_common_manager(emp_id_1, emp_id_2, manager_map):
if emp_id_1 not in manager_map or emp_id_2 not in manager_map:
return None
if emp_id_1 == emp_id_2:
return manager_map[emp_id_1]
ancestors = set()
current = emp_id_1
while current is not None:
ancestors.add(current)
current = manager_map.get(current)
current = emp_id_2
while current is not None:
if current in ancestors:
return current
current = manager_map.get(current)
return None
Complexity Summary
- Challenge 1: O(n) time, O(1) space
- Challenge 2: O(n log n) time with sorting, O(n) space
- Challenge 3: O(h) time per query, O(h) space
Common Mistakes
- Forgetting to handle multiple hierarchies (the example has two roots)
- Assuming the input is sorted by hierarchy or that parents appear before children
- In the ancestor search, not handling the case where one employee is the ancestor of the other
- Returning
Nonevs. the higher employee when one manages the other—both are valid if documented - Not reusing the indexes across all three functions, leading to redundant O(n) work per function call