Company Hierarchy Query System with Dynamic Updates
Data Structure DesignModel answerLast updated
Build a data structure to efficiently query employee roles and reporting counts in a company hierarchy, then extend it to handle dynamic additions.
You're building an internal tool to query a company's reporting structure. The hierarchy is provided as a list of [manager, report] pairs where each name is a unique string. The structure may have multiple top-level leaders (a forest rather than a single tree) but contains no cycles.
Design and implement a data structure that supports:
Part 1: lookUp(name) should return three pieces of information:
role: the string"mgr"if this person manages at least one direct report, otherwise"ic"(individual contributor)directReportCount: how many people report directly to this persontotalReportCount: the total size of their organization (all people in their reporting chain, not including themselves)
Part 2: Analyze the time and space complexity of your implementation.
Part 3: If your system will handle many more lookups than updates, how would you optimize it?
Part 4: If lookUp must run in O(1) time, what preprocessing would you perform and what would that cost?
Part 5: Extend your design to support add(managerName, reportName) which creates a new reporting relationship. If either person doesn't exist yet, add them to the system. After calling add, subsequent lookUp calls should reflect the updated structure. Discuss how this impacts your complexity analysis.
Your implementation should handle:
- Multiple disconnected reporting chains
- Validation to prevent cycles and duplicate manager assignments
- Efficient updates to aggregated counts
Include test cases demonstrating correctness.
Hints
Hint 1
Think about whether you want to compute subtree sizes on-demand or precompute them once
Hint 2
For O(1) lookups, you'll need to cache derived information—what exactly needs to be cached?
Hint 3
When adding a new edge, which nodes' counts are affected? Only the ancestors of the manager, not the entire tree
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is recognizing this as a forest traversal with subtree aggregation. We want to avoid recomputing subtree sizes on every query, so we'll precompute and cache all derived metrics.
Core Strategy
- Build the graph structure: Maintain adjacency lists and parent pointers while ingesting the pairs
- Precompute all subtree sizes: Use post-order traversal (children before parents) to aggregate counts bottom-up
- Cache everything for O(1) lookups: Store direct counts and total counts in hash tables
- Handle dynamic updates incrementally: When adding an edge, propagate the change up the ancestor chain
Data Structures
parent: dict[str, str]— maps each person to their manager (if any)children: dict[str, list[str]]— adjacency list of direct reportsdirect: dict[str, int]— count of immediate reports for each persontotal: dict[str, int]— count of all descendants (not including the person themselves)
Computing Subtree Totals
The total count for a manager equals the sum of 1 + total[child] across all children. This recursive definition means we must process children before their parents.
Algorithm:
- Find all roots (people with no manager)
- Run iterative DFS from each root to build a pre-order list (parents appear before children)
- Reverse that list and process it—now children are finalized before we compute their parents
- For each person, add
1 + total[person]to their manager's total
This works because in a forest, a person's descendants are exactly their children plus all those children's descendants, with no overlap.
Complexity Analysis (Parts 2-4)
Let N = number of people, E = number of edges, d = maximum depth of reporting chain.
| Operation | Time | Space |
|---|---|---|
| Initial construction | O(N + E) | O(N) |
| Naive lookUp (DFS each time) | O(subtree size), worst O(N) | O(N) |
| Preprocessed lookUp | O(1) | O(N) |
| Dynamic add | O(d), worst O(N) for chain | O(1) incremental |
Why precompute? In a read-heavy workload (typical for org charts), paying O(N) once to enable O(1) lookups beats O(N) per lookup. If you have Q queries, naive costs O(Q·N) while precomputed costs O(N + Q).
Dynamic Updates (Part 5)
When adding reportName under managerName:
-
Validation checks:
- Reject self-loops
- Reject if
reportNamealready has a different manager - Walk ancestors of
managerNameto detect ifreportNameis already above it (would create cycle)
-
Update graph structure: Add edge and increment
direct[managerName] -
Propagate count changes: The manager and all their ancestors gain
1 + total[reportName]descendants. Walk up the parent chain from the manager, incrementing each ancestor's total by this amount.
Why only ancestors? When you attach a subtree to a manager, only that manager's reporting chain gains new descendants. Siblings and other branches are unaffected.
Trade-off: O(d) per insertion is acceptable for occasional updates. For bulk inserts or very deep chains, consider batching updates and rebuilding from scratch in O(N) time, or switching to lazy recomputation where you mark nodes dirty and recompute on read.
Edge Cases and Validation
- Missing names in lookUp: Raise an error or return a default tuple like
("ic", 0, 0)—state your choice explicitly - Empty input or isolated individuals: Should work correctly with people having zero reports
- Duplicate pairs: Idempotent—ignore duplicates to avoid double-counting
- Two managers: Explicitly reject with an error
- Cycles: Detect during both initial construction and dynamic adds
- Deep chains: Use iteration instead of recursion to avoid stack overflow
Implementation
from typing import Dict, List, Tuple
class CompanyHierarchy:
def __init__(self, pairs: List[List[str]]):
self.parent: Dict[str, str] = {}
self.children: Dict[str, List[str]] = {}
self.direct: Dict[str, int] = {}
self.total: Dict[str, int] = {}
for mgr, rep in pairs:
self._add_edge(mgr, rep)
self._calculate_totals()
def _initialize_person(self, name: str) -> None:
"""Ensure person exists in all tracking structures."""
if name not in self.direct:
self.direct[name] = 0
self.total[name] = 0
self.children[name] = []
def _add_edge(self, mgr: str, rep: str) -> bool:
"""Create reporting relationship. Returns False if duplicate."""
if mgr == rep:
raise ValueError(f"Person cannot report to themselves: {mgr}")
self._initialize_person(mgr)
self._initialize_person(rep)
if rep in self.parent:
if self.parent[rep] == mgr:
return False # duplicate, skip
raise ValueError(f"{rep} already has manager {self.parent[rep]}")
self.parent[rep] = mgr
self.children[mgr].append(rep)
self.direct[mgr] += 1
return True
def _calculate_totals(self) -> None:
"""Precompute subtree sizes for all people."""
# Find roots (people with no manager)
roots = [p for p in self.direct if p not in self.parent]
# Build pre-order traversal (parents before children)
visit_order = []
stack = list(roots)
while stack:
person = stack.pop()
visit_order.append(person)
stack.extend(self.children[person])
# Cycle detection
if len(visit_order) != len(self.direct):
raise ValueError("Hierarchy contains cycle")
# Process in reverse (children before parents)
for person in reversed(visit_order):
if person in self.parent:
mgr = self.parent[person]
self.total[mgr] += 1 + self.total[person]
def lookUp(self, name: str) -> Tuple[str, int, int]:
"""Return (role, direct_count, total_count) for the person."""
if name not in self.direct:
raise KeyError(f"Person not found: {name}")
direct_count = self.direct[name]
role = "mgr" if direct_count > 0 else "ic"
return (role, direct_count, self.total[name])
def add(self, managerName: str, reportName: str) -> None:
"""Add new reporting relationship with incremental update."""
mgr, rep = managerName, reportName
if mgr == rep:
raise ValueError(f"Person cannot report to themselves: {mgr}")
self._initialize_person(mgr)
self._initialize_person(rep)
# Check if already exists
if self.parent.get(rep) == mgr:
return
# Check for existing manager
if rep in self.parent:
raise ValueError(f"{rep} already reports to {self.parent[rep]}")
# Cycle detection: rep cannot be ancestor of mgr
current = mgr
while current is not None:
if current == rep:
raise ValueError("Cannot add: would create cycle")
current = self.parent.get(current)
# Add the edge
self._add_edge(mgr, rep)
# Propagate count changes up ancestor chain
subtree_size = 1 + self.total[rep]
current = mgr
while current is not None:
self.total[current] += subtree_size
current = self.parent.get(current)
# Test cases
pairs = [
["Alice", "Bob"],
["Alice", "Carol"],
["Bob", "Dan"],
["Eve", "Frank"] # Separate tree
]
org = CompanyHierarchy(pairs)
assert org.lookUp("Alice") == ("mgr", 2, 3) # manages Bob, Carol, and Dan (via Bob)
assert org.lookUp("Bob") == ("mgr", 1, 1) # manages Dan
assert org.lookUp("Dan") == ("ic", 0, 0) # no reports
assert org.lookUp("Eve") == ("mgr", 1, 1) # manages Frank
org.add("Carol", "Grace")
assert org.lookUp("Carol") == ("mgr", 1, 1)
assert org.lookUp("Alice") == ("mgr", 2, 4) # now includes Grace
print("All tests passed!")
Common Mistakes
- Not handling forests: Assuming there's only one root
- Wrong traversal order: Computing parent totals before children are ready
- O(N) per add: Recomputing everything instead of incremental updates
- Forgetting cycle detection: Allowing invalid structures
- Off-by-one errors: Including/excluding the person themselves in total counts—be consistent with the problem definition