Subordinate Rollups Across an Org Hierarchy
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
An organization stores its reporting structure as a flat list of staff records. Each record is a dictionary with two keys:
'id'(int): a unique integer identifier for that person.'manager_id'(intorNone): the'id'of the person they report to directly, orNonewhen they sit at the top of a reporting tree.
Multiple people may have 'manager_id': None, meaning the company can consist of several independent reporting trees (a forest) with no circular reporting loops. Records may appear in any order in the input list.
Implement analyze_org_chart(employees) to summarize every person's reporting scope:
def analyze_org_chart(employees: List[Dict]) -> Dict[int, Dict]:
For each record in employees, compute three fields:
'direct'(int): how many people list this person as their'manager_id'.'total'(int): how many people sit anywhere beneath this person in their reporting subtree (both direct reports and all indirect levels below them).'is_manager'(bool):Trueif'direct' >= 1, orFalseif'direct' == 0.
Return a dictionary mapping each person's stringified identifier str(id) to {'is_manager': bool, 'direct': int, 'total': int}.
Examples
Example 1
Input:
employees = [
{'id': 100, 'manager_id': None},
{'id': 105, 'manager_id': 100},
{'id': 110, 'manager_id': 105},
{'id': 115, 'manager_id': 105},
{'id': 120, 'manager_id': 100},
]
Output:
{
'100': {'is_manager': True, 'direct': 2, 'total': 4},
'105': {'is_manager': True, 'direct': 2, 'total': 2},
'110': {'is_manager': False, 'direct': 0, 'total': 0},
'115': {'is_manager': False, 'direct': 0, 'total': 0},
'120': {'is_manager': False, 'direct': 0, 'total': 0},
}
Explanation: Staff member 100 directly manages 105 and 120 (direct = 2), while 105 directly manages 110 and 115 (direct = 2, total = 2). Counting both levels gives 100 a total reporting subtree of 4 people (105, 110, 115, 120). Staff members 110, 115, and 120 manage nobody, so is_manager is False and both counts are 0.
Example 2
Input:
employees = [
{'id': 50, 'manager_id': None},
{'id': 51, 'manager_id': 50},
{'id': 52, 'manager_id': 51},
{'id': 80, 'manager_id': None},
{'id': 81, 'manager_id': 80},
{'id': 90, 'manager_id': None},
]
Output:
{
'50': {'is_manager': True, 'direct': 1, 'total': 2},
'51': {'is_manager': True, 'direct': 1, 'total': 1},
'52': {'is_manager': False, 'direct': 0, 'total': 0},
'80': {'is_manager': True, 'direct': 1, 'total': 1},
'81': {'is_manager': False, 'direct': 0, 'total': 0},
'90': {'is_manager': False, 'direct': 0, 'total': 0},
}
Explanation: The input contains three separate trees rooted at 50, 80, and 90. In the first chain (50 -> 51 -> 52), 51 has 1 subordinate (52) and 50 has 1 direct report (51) plus 1 indirect report (52) for total = 2. In the second tree, 80 directly manages 81. Staff member 90 stands alone with 0 subordinates.
Example 3
Input:
employees = [
{'id': 42, 'manager_id': None},
]
Output:
{
'42': {'is_manager': False, 'direct': 0, 'total': 0},
}
Explanation: With only one person in the list and nobody reporting to 42, direct and total are both 0 and is_manager is False.
Constraints
0 <= len(employees) <= 100,000- Every
'id'inemployeesis a distinct integer (zero and negative integers are valid IDs). - Every non-
None'manager_id'refers to another record's'id', and the reporting graph contains no cycles. - Reporting chains may be up to
100,000levels deep.
Step-by-step walkthrough
Understand the goal and the hierarchy shape
Note: even though the type annotation writes
Dict[int, Dict], serialized JSON test expectations represent outer dictionary keys as strings ('100', not100), so we convert outer keys withstr(emp_id).Each staff entry has the form
{'id': int, 'manager_id': int or None}. Together, these upward reporting links form a forest — one or more separate trees with no loops, where each tree is rooted at someone whosemanager_idisNone.For every employee, we compute three values: -
direct: how many people name them asmanager_id(one level below). -total: how many people appear anywhere below them in their subtree (direct reports plus all indirect levels underneath). -is_manager:Truewhendirect > 0, orFalsewhendirect == 0.Example 1 hierarchy: [100] 100: direct = 2 (105, 120), total = 4 (105, 110, 115, 120), is_manager = True / \ [105] [120] 105: direct = 2 (110, 115), total = 2 (110, 115), is_manager = True / \ 120: direct = 0, total = 0, is_manager = False [110] [115] 110, 115: direct = 0, total = 0, is_manager = FalseWhy walking upward from every employee is too slow
A tempting first attempt starts at each employee, follows
manager_idupward until hittingNone, and adds1tototalfor every ancestor passed along the way.That brute-force walk gives the right answer on small inputs, which makes it handy for testing. On a narrow chain of
N = 100,000employees where1manages2,2manages3, and so on down to100,000, however, the bottom employee walks99,999links, the next walks99,998links, and so on:1 <- 2 <- 3 <- 4 <- ... <- 100,000Across everyone, that adds up to
1 + 2 + ... + 99,999 ≈ 5,000,000,000steps — far too slow forN = 100,000.Key idea: roll counts up from the bottom
Instead of re-walking shared management chains from every person, let each manager gather one precomputed total from each direct report.
Suppose manager
mhas direct reportsr1, r2, .... Once we already knowtotal_descendants[r]for a direct reportr, how many people doesr's branch contribute tom? -1forrthemselves, plus -total_descendants[r]for everyone beneathr.[100] total[100] = (1 + total[105]) + (1 + total[120]) / \ = (1 + 2) + (1 + 0) = 4 [105] [120] total[105] = (1 + 0) + (1 + 0) = 2, total[120] = 0 / \ [110] [115] total[110] = 0, total[115] = 0To apply this rule cleanly, we just need to finish every subordinate before computing their manager. Processing children before parents is called a post-order (bottom-up) traversal, and because each reporting link is combined once, the whole forest takes
O(N)time.Phase 1: Build the direct-reports map and collect roots
The input gives upward links (
emp -> manager_id), whereas tree traversal needs downward links (manager_id -> list of direct reports). A dictionary mapping each node to its list of immediate neighbors is called an adjacency list.We populate
direct_reportsin two linear passes: 1. Initializedirect_reports[emp["id"]] = []for every employee first, so input order never matters even when a subordinate appears before their manager. 2. Append eachemp_idtodirect_reports[manager_id], or appendemp_idtorootsifmanager_id is None. Notice we checkmanager_id is Noneexplicitly rather thanif not manager_id:, because0is a valid employee ID!# direct_reports: maps each employee_id -> list of direct report IDs, # e.g. {100: [105, 120], 105: [110, 115], 110: [], 115: [], 120: []}. # Pass 1 registers every employee ID first so input order does not matter. direct_reports: Dict[int, List[int]] = {} for emp in employees: direct_reports[emp["id"]] = [] # roots: top-level employee IDs who report to no one in the input, e.g. [50, 80, 90]. roots: List[int] = [] for emp in employees: emp_id = emp["id"] manager_id = emp["manager_id"] # Check `is None` explicitly because employee ID 0 is a valid manager. # Also treat an unlisted manager_id as a root so no employee is skipped. if manager_id is None or manager_id not in direct_reports: roots.append(emp_id) else: direct_reports[manager_id].append(emp_id)Phase 2: Obtain a bottom-up order iteratively
Writing a recursive helper looks short, but Python caps its call stack (the memory holding nested function calls waiting to return) at roughly 1,000 frames by default. On a 100,000-level chain, recursion raises
RecursionError.Instead, we maintain our own list
stackseeded withroots. On each iteration we popemp_id, append it tovisit_order, and push all ofemp_id's direct reports ontostack.Why does reversing
visit_ordergive a valid bottom-up order? Because a report is pushed ontostackonly after their manager has already been appended tovisit_order, so every manager sits earlier invisit_orderthan all of their subordinates:visit_order (forwards): managers always come BEFORE their reports (top-down) visit_order (reversed): reports always come BEFORE their managers (bottom-up!)Walking
reversed(visit_order)guaranteestotal_descendants[report_id]is already finalized whenever we sumtotal_descendants[emp_id]:# Phase 2: Visit every tree top-down using an explicit stack instead of # recursion, avoiding RecursionError on chains of up to 100,000 employees. # Because reports are pushed only AFTER their manager is recorded, every # manager appears earlier in visit_order than all of their reports. visit_order: List[int] = [] stack: List[int] = list(roots) while stack: emp_id = stack.pop() visit_order.append(emp_id) for report_id in direct_reports[emp_id]: stack.append(report_id) # Phase 3: Walk visit_order backwards (bottom-up) so every direct report's # descendant count is already finished before we compute their manager's count. # total_descendants: maps employee_id -> total direct + indirect reports. total_descendants: Dict[int, int] = {} for emp_id in reversed(visit_order): descendant_count = 0 for report_id in direct_reports[emp_id]: # Add 1 for the direct report themselves, plus everyone below them. descendant_count += 1 + total_descendants[report_id] total_descendants[emp_id] = descendant_countPhase 3: Format the output dictionary
With every count ready: -
direct_countislen(direct_reports[emp_id]). -is_managerisdirect_count > 0. -totalistotal_descendants[emp_id].We store each entry under
result[str(emp_id)]to match the stringified outer keys expected by the test suite.# Phase 4: Build the output dictionary. # The judge's JSON test cases store outer keys as strings (e.g. '1', not 1). result: Dict[str, Dict[str, Any]] = {} for emp in employees: emp_id = emp["id"] direct_count = len(direct_reports[emp_id]) result[str(emp_id)] = { "is_manager": direct_count > 0, "direct": direct_count, "total": total_descendants[emp_id], }Trace on a three-tree forest (Example 2)
Let's trace Example 2:
50(root),51 -> 50,52 -> 51,80(root),81 -> 80, and90(root).Tree A: [50] Tree B: [80] Tree C: [90] | | [51] [81] | [52] 1. Adjacency & roots: direct_reports = {50: [51], 51: [52], 52: [], 80: [81], 81: [], 90: []} roots = [50, 80, 90] 2. Explicit stack walk (pop from end): start stack = [50, 80, 90] pop 90 -> visit_order = [90], stack = [50, 80] pop 80 -> visit_order = [90, 80], stack = [50, 81] pop 81 -> visit_order = [90, 80, 81], stack = [50] pop 50 -> visit_order = [90, 80, 81, 50], stack = [51] pop 51 -> visit_order = [90, 80, 81, 50, 51], stack = [52] pop 52 -> visit_order = [90, 80, 81, 50, 51, 52], stack = [] 3. Bottom-up pass over reversed(visit_order) = [52, 51, 50, 81, 80, 90]: emp 52: no reports -> total_descendants[52] = 0 emp 51: (1 + total_descendants[52]) = 1 + 0 -> total_descendants[51] = 1 emp 50: (1 + total_descendants[51]) = 1 + 1 -> total_descendants[50] = 2 emp 81: no reports -> total_descendants[81] = 0 emp 80: (1 + total_descendants[81]) = 1 + 0 -> total_descendants[80] = 1 emp 90: no reports -> total_descendants[90] = 0That produces
total = 2for'50',total = 1for'51'and'80', andtotal = 0for'52','81', and'90'.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def analyze_org_chart(employees: List[Dict]) -> Dict[int, Dict]: # direct_reports: maps each employee_id -> list of direct report IDs, # e.g. {100: [105, 120], 105: [110, 115], 110: [], 115: [], 120: []}. # Pass 1 registers every employee ID first so input order does not matter. direct_reports: Dict[int, List[int]] = {} for emp in employees: direct_reports[emp["id"]] = [] # roots: top-level employee IDs who report to no one in the input, e.g. [50, 80, 90]. roots: List[int] = [] for emp in employees: emp_id = emp["id"] manager_id = emp["manager_id"] # Check `is None` explicitly because employee ID 0 is a valid manager. # Also treat an unlisted manager_id as a root so no employee is skipped. if manager_id is None or manager_id not in direct_reports: roots.append(emp_id) else: direct_reports[manager_id].append(emp_id) # Phase 2: Visit every tree top-down using an explicit stack instead of # recursion, avoiding RecursionError on chains of up to 100,000 employees. # Because reports are pushed only AFTER their manager is recorded, every # manager appears earlier in visit_order than all of their reports. visit_order: List[int] = [] stack: List[int] = list(roots) while stack: emp_id = stack.pop() visit_order.append(emp_id) for report_id in direct_reports[emp_id]: stack.append(report_id) # Phase 3: Walk visit_order backwards (bottom-up) so every direct report's # descendant count is already finished before we compute their manager's count. # total_descendants: maps employee_id -> total direct + indirect reports. total_descendants: Dict[int, int] = {} for emp_id in reversed(visit_order): descendant_count = 0 for report_id in direct_reports[emp_id]: # Add 1 for the direct report themselves, plus everyone below them. descendant_count += 1 + total_descendants[report_id] total_descendants[emp_id] = descendant_count # Phase 4: Build the output dictionary. # The judge's JSON test cases store outer keys as strings (e.g. '1', not 1). result: Dict[str, Dict[str, Any]] = {} for emp in employees: emp_id = emp["id"] direct_count = len(direct_reports[emp_id]) result[str(emp_id)] = { "is_manager": direct_count > 0, "direct": direct_count, "total": total_descendants[emp_id], } return result✅ Submit now — all tests should pass.
Intuition & how it works
Imagine taking headcount across a large company. Instead of having every employee send separate pings up to their supervisor, director, VP, and CEO, it is far faster to roll totals up from the bottom: staff with nobody reporting to them report 0, each frontline lead adds 1 + count from each direct report and hands one combined number up to their director, and so on to the top.
The naive method — starting at every person and following manager_id links upward until None — repeats work along shared chains. When 100,000 people form a single vertical chain (1 manages 2, 2 manages 3, ...), walking upward from everyone takes 1 + 2 + ... + 99,999 ≈ 5 billion steps and times out. A textbook recursive traversal also fails on that chain because Python's call stack (the memory storing active nested function calls that have not returned yet) defaults to roughly 1,000 frames and raises RecursionError.
We get both linear speed and stack safety by building an adjacency list (a dictionary mapping each manager ID to their list of direct report IDs) and traversing top-down with an explicit list stack. Take Example 1 ([100 (None), 105 (mgr 100), 110 (mgr 105), 115 (mgr 105), 120 (mgr 100)]):
1. direct_reports becomes {100: [105, 120], 105: [110, 115], 110: [], 115: [], 120: []} and roots = [100].
2. Popping from stack records each manager before pushing their reports, giving visit_order = [100, 120, 105, 115, 110].
3. Iterating over visit_order in reverse ([110, 115, 105, 120, 100]) produces a post-order (bottom-up) order — an ordering where every subordinate finishes before their manager: total[110] = 0, total[115] = 0, total[105] = (1 + 0) + (1 + 0) = 2, total[120] = 0, and total[100] = (1 + 2) + (1 + 0) = 4.
Complexity
- Time: O(N), where
Nislen(employees). We scan theNdictionaries twice with O(1) hash-map lookups to builddirect_reportsandroots, push and pop each of theNIDs once onstack, traverse each of the at mostN - 1reporting links once during the bottom-up sum, and run one final O(N) pass to buildresult. - Space: O(N).
direct_reportsholdsNkeys and at mostN - 1subordinate IDs across all lists, whileroots,stack,visit_order,total_descendants, andresulteach store at mostNentries. Because no recursive calls are made, Python's call stack uses O(1) space at any hierarchy depth.
Edge cases
- Empty list (
[]):rootsandvisit_orderstay empty, returning{}. - Single standalone employee (
[{'id': 42, 'manager_id': None}]):directis0,totalis0, andis_managerisFalse(Example 3). - Multiple independent hierarchies (a forest): A forest is a collection of separate trees with multiple
manager_id is Noneroots. Seedingstack = list(roots)visits every tree cleanly without mixing counts across them (Example 2). - Deep chain of 100,000 levels: Processed iteratively on the heap-allocated
stacklist without hittingRecursionError. - Subordinates listed before managers: Registering every
emp["id"]indirect_reportsduring Pass 1 before wiringmanager_idedges in Pass 2 makes input ordering irrelevant. - Employee ID
0: Because0is a valid integer ID, testingmanager_id is None(rather thanif not manager_id:) avoids misclassifying subordinates of manager0as roots. - Stringified outer keys: Outer dictionary keys use
str(emp_id)('100','42') to match serialized JSON test expectations.
Common mistakes
- Omitting
+ 1in1 + total_descendants[report_id]: Summing onlytotal_descendants[report_id]leaves every manager at0because leaf employees havetotal = 0and never count themselves toward their manager. - Using recursion on deep chains: Recursive DFS passes small tests yet crashes with
RecursionErroronce reporting depth passes ~1,000 levels. - Iterating
visit_orderforwards during aggregation: Invisit_order, managers appear before their subordinates, so summing forwards readstotal_descendants[report_id]before it has been computed. - Testing truthiness (
if emp["manager_id"]:) instead ofis not None: In Python,bool(0)evaluates toFalse, silently dropping all direct reports of manager0. - Walking upward from every employee: Easy to write as a test oracle, but degrades to O(N²) time on deep chains.
Alternative approaches
- Bottom-up leaf peeling (Kahn's topological sort): Topological sort processes nodes whose prerequisites are all resolved first. Track each employee's remaining unresolved direct reports (
remaining[m] = direct[m]), enqueue all leaf contributors (remaining == 0), and whenever an employee is dequeued, add1 + total[emp]to their manager and decrementremaining[manager], enqueuing the manager whenremaining[manager]reaches0. This also runs in O(N) time and O(N) space without storing child lists. - Recursive DFS: Brief for shallow hierarchies, but unsafe in Python when depth can reach
100,000.
Follow-up questions
- What happens if corrupted HR data introduces a reporting loop, and how would you detect it? Every person inside a cycle reports to someone else in that cycle, so a cyclic component has no
manager_id is Noneroot and is never reached when starting fromroots. That gives a fast O(N) check right away: iflen(visit_order) < len(employees)after the stack traversal, at least one loop exists! To isolate the exact loop, followmanager_idpointers from each unvisited person using three states (unvisited,visitingon the current walk, anddone); stepping onto avisitingID pinpoints the cycle, and since subordinate counts on a loop are ill-defined, you should raise an error or report the offending IDs. - Which data structures support fast subordinate-count maintenance when people frequently transfer between managers? Keep
manager_of[x]andtotal[x]for each person: reassigning employeex(whose subtree carriess = 1 + total[x]people includingx) from managerAto managerBsimply subtractssalongA's ancestor chain and addssalongB's ancestor chain in O(depth) time, after verifyingBis not insidex's own subtree (which would form a cycle). If chains can be 100,000 levels deep and require worst-case guarantees, an Euler tour tree — a structure that flattens a tree walk into a balanced binary search tree so every subtree occupies one contiguous range — supports cutting, relinking, and querying subtree sizes in O(log N) time per transfer. - How would you reconstruct the upward reporting path from a given staff member to their root executive? Build a dictionary
manager_ofmapping eachemp["id"]toemp["manager_id"], startcurrat the queried staff ID, and repeatedly appendcurrand advancecurr = manager_of[curr]untilcurr is None. This runs in O(depth) time and O(depth) space for the returned chain (tracking aseenset along the walk stops immediately if cycles are possible). If you also need millions of O(1) "isAaboveB?" checks on a static org chart, record DFS entry and exit timestamps once in O(N) time:Ais an ancestor ofBif and only ifA's[entry, exit]interval enclosesB's.
Follow-up questions
- What happens if corrupted HR data introduces a reporting loop, and how would you detect it?
- Which data structures support fast subordinate-count maintenance when people frequently transfer between managers?
- How would you reconstruct the upward reporting path from a given staff member to their root executive?
Similar questions
- Constant-Time Org-Chart Subtree Lookup
- JSON User Profile Pipeline: Batch vs. Streaming
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance