Constant-Time Org-Chart Subtree Lookup
Easy · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Model a company's reporting hierarchy in memory from an initial list of two-element string pairs [manager, report], where report works directly under manager. Every employee is identified by a unique string name, each person reports to at most one direct manager, and valid hierarchies contain no reporting loops—forming a forest of zero or more independent trees.
Design the OrgChart class so read traffic is served in constant expected time after linear-time initialization, while also supporting live additions to the hierarchy:
OrgChart(pairs: List[List[str]]) -> NoneConstructs the hierarchy and precomputes any needed summary counts. RaisesValueErrorif any employee is assigned two managers or ifpairsforms a cycle (including self-reporting).look_up(name: str) -> Tuple[str, int, int]Returns(role, direct_report_count, total_report_count)inO(1)expected time:role:"mgr"whennamesupervises at least1immediate subordinate, or"ic"otherwise.direct_report_count: count of immediate subordinates reporting directly toname.total_report_count: count of all direct and indirect subordinates anywhere beneathname(excludingname). RaisesKeyErrorwhennameis not registered in the chart.
add(manager: str, report: str) -> NoneAttachesreportas an immediate subordinate ofmanager, registering either name if unseen so far. Whenreportis already a top-level leader with subordinates,report's entire subtree moves underneathmanager. RaisesValueError—leaving all existing state untouched—ifreportalready has a manager or if linkingmanagertoreportwould close a cycle (includingmanager == report).
Examples
Example 1
Input:
chart = OrgChart([
["Dana", "Eli"],
["Dana", "Faye"],
["Dana", "Gabe"],
["Eli", "Hana"],
["Eli", "Ivan"],
["Hana", "Jude"],
])
chart.look_up("Dana")
chart.look_up("Eli")
chart.look_up("Hana")
chart.look_up("Faye")
Output:
("mgr", 3, 6)
("mgr", 2, 3)
("mgr", 1, 1)
("ic", 0, 0)
Explanation: "Dana" directly supervises "Eli", "Faye", and "Gabe" (3 direct subordinates), plus "Hana", "Ivan", and "Jude" further down (6 total subordinates). "Eli" supervises "Hana" and "Ivan" directly and "Jude" indirectly (3 total). "Faye" supervises nobody, so her role is "ic" with counts (0, 0).
Example 2
Input:
chart = OrgChart([["Kira", "Leo"], ["Mina", "Noah"], ["Mina", "Omar"]])
chart.look_up("Kira") # -> ("mgr", 1, 1)
chart.look_up("Mina") # -> ("mgr", 2, 2)
chart.add("Leo", "Mina")
chart.look_up("Leo") # -> ("mgr", 1, 3)
chart.look_up("Kira") # -> ("mgr", 1, 4)
chart.add("Omar", "Zoe")
chart.look_up("Kira") # -> ("mgr", 1, 5)
chart.add("Zoe", "Kira") # -> raises ValueError
Explanation: Initially "Kira" and "Mina" head two separate trees. Calling add("Leo", "Mina") places "Mina" and her 2 subordinates under "Leo", giving "Leo" 1 + 2 = 3 total subordinates and bumping "Kira" from 1 to 4. Adding brand-new hire "Zoe" under "Omar" increments "Omar", "Mina", "Leo", and "Kira" by 1. Attempting add("Zoe", "Kira") would create a loop from "Kira" down to "Zoe" and back to "Kira", so ValueError is raised without altering any counts.
Example 3
Input:
OrgChart([["Vera", "Wes"], ["Tori", "Wes"]]) # -> raises ValueError
OrgChart([["Vera", "Wes"]]).look_up("Quinn") # -> raises KeyError
Explanation: "Wes" cannot report to both "Vera" and "Tori", so construction fails with ValueError. Querying "Quinn", who never appeared in any pair or add call, raises KeyError.
Constraints
0 <= len(pairs) <= 10^5- Every entry in
pairsis a two-string list[manager, report]with non-empty names. - Chains may be thousands of levels deep (
O(n)height), so initialization and updates must not hit Python's recursion limit. - Target complexity for
ndistinct employees:O(n)preprocessing time andO(n)space in__init__,O(1)expected time perlook_up, andO(d)time peraddwheredis the number of ancestors abovemanager.
Step-by-step walkthrough
Restate the problem and clarify edge cases
We receive reporting links
[manager, report]where employee names are unique strings. Because each person reports to at most one manager and no loops exist, the hierarchy forms a forest—zero or more independent trees, each headed by a top-level leader with no manager.Calling
look_up(name)must return(role, direct_report_count, total_report_count):direct_report_count: how many immediate subordinates report directly toname(their out-degree, or child count).total_report_count: how many employees sit anywhere beneathnamein their subtree (all descendants—direct subordinates, their subordinates, and so on—excludingname).role:"mgr"whendirect_report_count >= 1, otherwise"ic"(individual contributor).
Dana look_up("Dana") -> ("mgr", direct=3, total=6) [Eli, Faye, Gabe, Hana, Ivan, Jude] / | \ look_up("Eli") -> ("mgr", direct=2, total=3) [Hana, Ivan, Jude] Eli Faye Gabe look_up("Hana") -> ("mgr", direct=1, total=1) [Jude] / \ look_up("Faye") -> ("ic", direct=0, total=0) [] Hana Ivan | JudeGood engineering practice means locking down edge-case behavior right away:
- Querying an unseen name raises
KeyError(returning("ic", 0, 0)would mask misspelled names). add(manager, report)registers either employee if brand new, and ifreportis an existing top-level leader, their entire subtree moves underneathmanager.- Invalid links—assigning a second manager,
manager == report, or making an ancestor report to one of their own descendants—raiseValueErrorwithout changing any existing state.
Brute force: walk the subtree on every lookup
The simplest baseline stores only each employee's list of immediate subordinates (
children[name]) and runs a depth-first search (DFS) downward fromnameon everylook_up(name)call:def count_descendants_on_demand(children, name): total = 0 stack = list(children[name]) while stack: person = stack.pop() total += 1 stack.extend(children[person]) return totalWhy does this break down under heavy read traffic?
- Constructing
childrentakesO(n)time andO(n)space fornemployees. - Each
look_up(name)visits every descendant ofname:O(1)on a leaf contributor, butO(n)on a company-wide executive. - With
100,000employees and100,000directory queries hitting senior leaders, the service performs up to100,000 * 100,000 = 10^10node visits—recounting identical subtrees over and over.
- Constructing
Key idea: precompute subtree totals bottom-up in O(n)
Observe how any manager's subtree total builds directly from their immediate subordinates' totals. Each child
childcontributes 1 (forchildthemselves) plustotal[child](everyone beneathchild):total[leaf] = 0 total[person] = sum over each child in children[person] of (1 + total[child])Evaluating
totalfrom leaves upward toward roots—visiting every child before its manager—ensures every term on the right-hand side is already known. Each reporting edge is read once, so precomputingtotalacross the entire forest takesO(n)time andO(n)extra space (one integer per employee).That directly addresses the complexity trade-off:
- Read-heavy optimization: compute
total[person]once up front instead of walking subtrees during reads. - Constant-time lookup: with
self.childrenandself.totalbuilt inO(n)preprocessing time andO(n)space,look_up(name)simply readslen(self.children[name])andself.total[name]inO(1)expected time.
- Read-heavy optimization: compute
Store the forest in three dictionaries
We keep three hash maps synchronized:
self.children: maps every known employee to their list of immediate subordinates—including leaf contributors whose list is[]. Registering both endpoints of every pair ensures leaf employees are never lost.self.manager: mapsreport -> manageronly for employees who have a manager. Top-level roots are simply the employees absent fromself.manager.self.total: maps every known employee to their precomputed descendant count.
def __init__(self, pairs: List[List[str]]) -> None: # self.children: maps EVERY known person -> list of direct reports, e.g. {"A": ["B", "C"], "C": []} self.children: Dict[str, List[str]] = {} # self.manager: maps report -> single manager (roots have no entry), e.g. {"B": "A", "C": "A"} self.manager: Dict[str, str] = {} # self.total: maps EVERY known person -> count of all descendants, e.g. {"A": 5, "C": 0} self.total: Dict[str, int] = {} # Phase 1: Register every person and wire manager -> report edges, rejecting duplicate managers. for manager, report in pairs: self._ensure(manager) self._ensure(report) if report in self.manager: raise ValueError(report + " already has a manager") self.manager[report] = manager self.children[manager].append(report) # Phase 2: Precompute subtree totals for every person so look_up runs in O(1) time. self._compute_totals() def _ensure(self, name: str) -> None: # Register a person on first sight so leaf individual contributors also exist in self.children. if name not in self.children: self.children[name] = [] self.total[name] = 0Because Phase 1 wires all edges before Phase 2 starts,
pairscan arrive in any order—even when a subordinate's pair appears earlier than their manager's pair.Compute totals iteratively and detect cycles
A recursive
dfs(person)helper is tempting, but CPython's default call-stack limit is1,000frames: a deep vertical chain of5,000managers (emp0 -> emp1 -> ... -> emp4999) would crash withRecursionError.An explicit stack produces a clean bottom-up order in two passes:
- Push every root (
name not in self.manager) ontostack, popperson, appendpersontoorder, and pushperson's children. Because children are pushed after their manager is popped, every manager precedes all of their descendants inorder. - Iterate over
reversed(order). Now every child precedes its manager—the exact leaf-to-root order needed!
Cycle detection falls out automatically: once Phase 1 guarantees at most one manager per person, any cycle (
Kira -> Leo -> Kira) has no root (KiraandLeoboth have a manager) and is never reached fromstack. Thereforelen(order) != len(self.children)holds if and only if a cycle exists.def _compute_totals(self) -> None: # Iterative DFS from all roots avoids Python's ~1,000-frame recursion limit on deep chains. order: List[str] = [] stack: List[str] = [] for name in self.children: if name not in self.manager: stack.append(name) while stack: person = stack.pop() order.append(person) for child in self.children[person]: stack.append(child) # With <= 1 manager per person, a cycle has no root and is never reached from stack. if len(order) != len(self.children): raise ValueError("the reporting pairs contain a cycle") # Every child was pushed after its manager, so reversed(order) visits children before managers. for person in reversed(order): subtree_reports = 0 for child in self.children[person]: subtree_reports += 1 + self.total[child] self.total[person] = subtree_reports- Push every root (
Answer look_up in O(1) time
With
self.childrenandself.totalready,look_upperforms zero traversal: Python lists store their length directly (O(1)), andself.total[name]is a single hash-map read (O(1)expected).def look_up(self, name: str) -> Tuple[str, int, int]: if name not in self.children: raise KeyError(name) # O(1) reads: Python stores list length, and total descendants was precomputed. direct_count = len(self.children[name]) role = "mgr" if direct_count > 0 else "ic" return (role, direct_count, self.total[name])Follow-up: support dynamic add in O(depth) time
Consider Example 2 when we call
add("Leo", "Mina")while"Mina"already supervises"Noah"and"Omar"(total["Mina"] = 2). Do we need to rebuild totals across the entire company?No—check whose subtree changes when
"Mina"attaches under"Leo":Before add("Leo", "Mina"): After add("Leo", "Mina"): Kira (total=1) Kira (total = 1 + 3 = 4) <-- ancestor gains 1 + total["Mina"] = 3 | | Leo (total=0) Mina (total=2) Leo (total = 0 + 3 = 3) <-- manager gains 1 + total["Mina"] = 3 / \ | Noah Omar Mina (total=2, unchanged) / \ Noah Omar (totals=0, unchanged)Only
managerand the ancestor chain abovemanagerchange, and each one increases bygained_reports = 1 + self.total[report](1forreportplus everyone already inreport's subtree).Validate before mutating any dictionary so a rejected
addnever leaves partial edits behind:reportmust not already have a manager (report not in self.manager).- Walking upward from
managerviaself.managermust never encounterreport(catching bothmanager == reportandmanagersitting insidereport's subtree).
def add(self, manager: str, report: str) -> None: # Validate BEFORE mutating state so a rejected add leaves the chart completely untouched. if report in self.manager: raise ValueError(report + " already has a manager") # Walk up from manager to its root: hitting report (including manager == report) means a cycle. ancestor: Optional[str] = manager while ancestor is not None: if ancestor == report: raise ValueError("adding this edge would create a cycle") ancestor = self.manager.get(ancestor) # Safe to mutate: register any brand-new names and link manager -> report. self._ensure(manager) self._ensure(report) self.manager[report] = manager self.children[manager].append(report) # Only manager and manager's ancestors change: each gains report (1) plus report's existing team. gained_reports = 1 + self.total[report] ancestor = manager while ancestor is not None: self.total[ancestor] += gained_reports ancestor = self.manager.get(ancestor)addwalks the ancestor chain twice (once to check for cycles, once to addgained_reports), takingO(d)time wheredismanager's depth (~5–12hops in typical companies,O(n)worst case on a single chain), while preservingO(1)look_up.Walk through Example 1 and Example 2
Trace Example 1 (
[["Dana", "Eli"], ["Dana", "Faye"], ["Dana", "Gabe"], ["Eli", "Hana"], ["Eli", "Ivan"], ["Hana", "Jude"]]):1. Build maps: Only "Dana" has no manager -> stack starts at ["Dana"]. Iterative DFS pops and pushes children: order = ["Dana", "Gabe", "Faye", "Eli", "Ivan", "Hana", "Jude"] (7 == 7 people, no cycles). 2. Bottom-up pass over reversed(order) = ["Jude", "Hana", "Ivan", "Eli", "Faye", "Gabe", "Dana"]: person="Jude": children=[] -> total["Jude"] = 0 person="Hana": children=["Jude"] -> total["Hana"] = (1 + 0) = 1 person="Ivan": children=[] -> total["Ivan"] = 0 person="Eli": children=["Hana", "Ivan"] -> total["Eli"] = (1 + 1) + (1 + 0) = 3 person="Faye": children=[] -> total["Faye"] = 0 person="Gabe": children=[] -> total["Gabe"] = 0 person="Dana": children=["Eli","Faye","Gabe"] -> total["Dana"] = (1 + 3) + (1 + 0) + (1 + 0) = 6 3. Constant-time lookups: look_up("Dana") -> ("mgr", 3, 6) look_up("Eli") -> ("mgr", 2, 3) look_up("Faye") -> ("ic", 0, 0)Then trace Example 2's dynamic updates on
[["Kira", "Leo"], ["Mina", "Noah"], ["Mina", "Omar"]]:1. Merge team: add("Leo", "Mina") Walk up from "Leo": visits "Leo" -> "Kira" -> None (never hits "Mina", valid). gained_reports = 1 + total["Mina"] = 1 + 2 = 3. total["Leo"] becomes 0 + 3 = 3; total["Kira"] becomes 1 + 3 = 4. 2. Add new hire: add("Omar", "Zoe") gained_reports = 1 + 0 = 1 -> bumps "Omar" (1), "Mina" (3), "Leo" (4), and "Kira" (5). 3. Rejected cycle: add("Zoe", "Kira") Walk up from "Zoe": "Zoe" -> "Omar" -> "Mina" -> "Leo" -> "Kira" == report -> raises ValueError!Complete solution
from typing import Dict, List, Optional, Tuple class OrgChart: """In-memory org chart built from [manager, direct_report] pairs. Names are unique. The pairs form a forest: every person has at most one manager and there are no cycles. """ def __init__(self, pairs: List[List[str]]) -> None: """Build the chart. Raise ValueError if someone has two managers or the pairs form a cycle.""" # self.children: maps EVERY known person -> list of direct reports, e.g. {"A": ["B", "C"], "C": []} self.children: Dict[str, List[str]] = {} # self.manager: maps report -> single manager (roots have no entry), e.g. {"B": "A", "C": "A"} self.manager: Dict[str, str] = {} # self.total: maps EVERY known person -> count of all descendants, e.g. {"A": 5, "C": 0} self.total: Dict[str, int] = {} # Phase 1: Register every person and wire manager -> report edges, rejecting duplicate managers. for manager, report in pairs: self._ensure(manager) self._ensure(report) if report in self.manager: raise ValueError(report + " already has a manager") self.manager[report] = manager self.children[manager].append(report) # Phase 2: Precompute subtree totals for every person so look_up runs in O(1) time. self._compute_totals() def _ensure(self, name: str) -> None: # Register a person on first sight so leaf individual contributors also exist in self.children. if name not in self.children: self.children[name] = [] self.total[name] = 0 def _compute_totals(self) -> None: # Iterative DFS from all roots avoids Python's ~1,000-frame recursion limit on deep chains. order: List[str] = [] stack: List[str] = [] for name in self.children: if name not in self.manager: stack.append(name) while stack: person = stack.pop() order.append(person) for child in self.children[person]: stack.append(child) # With <= 1 manager per person, a cycle has no root and is never reached from stack. if len(order) != len(self.children): raise ValueError("the reporting pairs contain a cycle") # Every child was pushed after its manager, so reversed(order) visits children before managers. for person in reversed(order): subtree_reports = 0 for child in self.children[person]: subtree_reports += 1 + self.total[child] self.total[person] = subtree_reports def look_up(self, name: str) -> Tuple[str, int, int]: """Return (role, direct_report_count, total_report_count) for name. role is "mgr" if name has at least one direct report, otherwise "ic". total_report_count counts every descendant, not only direct reports. Raise KeyError if name is not in the chart. """ if name not in self.children: raise KeyError(name) # O(1) reads: Python stores list length, and total descendants was precomputed. direct_count = len(self.children[name]) role = "mgr" if direct_count > 0 else "ic" return (role, direct_count, self.total[name]) def add(self, manager: str, report: str) -> None: """Make report a direct report of manager, creating either person if new. If report already manages people, the whole team moves with them. Raise ValueError, leaving the chart unchanged, if report already has a manager or if the new edge would create a cycle (including manager == report). """ # Validate BEFORE mutating state so a rejected add leaves the chart completely untouched. if report in self.manager: raise ValueError(report + " already has a manager") # Walk up from manager to its root: hitting report (including manager == report) means a cycle. ancestor: Optional[str] = manager while ancestor is not None: if ancestor == report: raise ValueError("adding this edge would create a cycle") ancestor = self.manager.get(ancestor) # Safe to mutate: register any brand-new names and link manager -> report. self._ensure(manager) self._ensure(report) self.manager[report] = manager self.children[manager].append(report) # Only manager and manager's ancestors change: each gains report (1) plus report's existing team. gained_reports = 1 + self.total[report] ancestor = manager while ancestor is not None: self.total[ancestor] += gained_reports ancestor = self.manager.get(ancestor)✅ Submit now — all tests should pass.
Intuition & how it works
Picture HR asking every leader in an organization how many employees sit beneath them. Rather than having an executive walk floor by floor recounting desks on every query, each leaf employee records 0, each first-line supervisor sums 1 + each subordinate's count onto their badge, and those numbers roll upward once to directors and VPs. After that single pass, any look_up answers immediately by reading the person's badge—and whenever a new hire or existing team attaches under M, only M and the chain of managers above M add the incoming headcount to their badges.
Skipping preprocessing and running a depth-first search (DFS) through name's subtree (all direct and indirect subordinates below name) on each look_up is fine for occasional queries, but querying a top-level root traverses up to n employees (O(n) per read). Under heavy read load—such as 100,000 employees and 100,000 profile views—re-traversing identical subtrees wastes billions of node visits.
Walk through a compact slice of our sample hierarchy with [["Dana", "Eli"], ["Dana", "Faye"], ["Eli", "Hana"]]:
- Wire links:
"Dana"supervises["Eli", "Faye"],"Eli"supervises["Hana"], and"Faye"and"Hana"supervise[]. Only"Dana"lacks a manager, making"Dana"the root. - Bottom-up pass (
Hana, Faye, Eli, Dana):total["Hana"] = 0andtotal["Faye"] = 0; nexttotal["Eli"] = 1 + total["Hana"] = 1; finallytotal["Dana"] = (1 + total["Eli"]) + (1 + total["Faye"]) = 2 + 1 = 3. - Instant lookup:
look_up("Dana")readslen(children["Dana"]) = 2andtotal["Dana"] = 3, returning("mgr", 2, 3)inO(1)time. - Dynamic
add("Faye", "Zoe"):gained_reports = 1 + 0 = 1; walking upwardFaye -> Danaupdatestotal["Faye"]from0to1("Faye"flips to"mgr") andtotal["Dana"]from3to4, without touching"Eli"or"Hana".
Complexity
Let n be the number of distinct employees in the chart and d be the number of ancestors above an employee (their tree depth; d <= n - 1, and typically d <= 12 in real organizations).
| Operation | Naive DFS per lookup | Precomputed totals (this solution) |
|---|---|---|
Preprocessing (__init__) |
O(n) time, O(n) space |
O(n) time, O(n) space |
look_up(name) |
O(subtree size), O(n) worst case |
O(1) expected time |
add(manager, report) |
O(d) with cycle check (O(1) without) |
O(d) time (O(n) worst-case chain) |
- Preprocessing time —
O(n): in a forest (a cycle-free collection of trees where every node has at most one parent),nemployees have at mostn - 1reporting links. We scanpairsonce to fill our dictionaries, push and pop each employee once during the iterative stack traversal, and inspect each link once more during the reversed bottom-up pass. - Space —
O(n):self.children,self.manager, andself.totalhold at mostnkeys each, and allchildrenlists combined store at mostn - 1string references. The temporarystackandorderlists during setup also holdnnames. look_uptime —O(1)expected: checking membership inself.children, reading Python's cached list length (len(...)), and readingself.total[name]require two hash-map lookups plus one integer read (treating short string hashing asO(1)).addtime —O(d): we walk upward alongself.managerfrommanagerto its root once to confirmreportis not an ancestor (blocking cycles), then walk the samedancestors once more to add1 + self.total[report].
Edge cases
- Empty chart (
pairs = []): initializes cleanly so anylook_upraisesKeyError, while a subsequentadd("Kira", "Leo")registers both employees. - Leaf contributors and multiple roots: employees appearing only as
reportgetchildren[name] = [](("ic", 0, 0)), and separate top-level leaders form independent trees in the forest. - Unordered input pairs:
[["Eli", "Hana"], ["Dana", "Eli"]]produces the exact same counts as[["Dana", "Eli"], ["Eli", "Hana"]]because all edges are wired before traversal begins. - Deep chains (
5,000levels): driving traversal with an explicit Pythonstacklist rather than recursive calls avoids CPython's ~1,000-frameRecursionError. - Merging an existing team via
add: attaching top-level leader"Mina"(who already supervises2people) under"Leo"adds1 + 2 = 3—not1—to"Leo"and every ancestor above"Leo". - Rejected updates leave state untouched: duplicate managers, self-loops (
add("Kira", "Kira")oradd("Fresh", "Fresh")), and ancestor loops (add("Zoe", "Kira")) raiseValueErrorbefore_ensuremutates any dictionary.
Common mistakes
- Counting
namethemselves insidetotal_report_count(off-by-one) or returning only immediate subordinates instead of the full subtree. - Forgetting to add
reporttoself.childrenwhen they supervise nobody, causinglook_upon leaf contributors to raiseKeyError. - Using recursive post-order DFS, which passes shallow examples of height 4 but crashes with
RecursionErroron skewed chains of 1,500+ employees. - Incrementing ancestors by
+1instead of1 + self.total[report]insideadd, undercounting whenever an existing leader brings a team along. - Updating only the immediate
managerinaddwhile forgetting higher-level ancestors—or rerunning anO(n)full-chart pass on every singleadd. - Calling
_ensureor mutatingself.childrenbefore validating cycles, leaving phantom employees behind after raisingValueError.
Alternative approaches
- Lazy memoization on read: compute
total[name]via DFS on first query and cache it. Eachaddstill has to invalidateO(d)ancestors, and the next query on a root drops back toO(n)—making eager updates simpler and consistentlyO(1)on reads. - Dirty flag for bulk writes: if thousands of
addoperations arrive in a batch with zero reads in between,addcan validate and flipdirty = True, deferring oneO(n)_compute_totals()pass until the nextlook_up(O(n + k)forkwrites rather thanO(k * d)). - Link-cut / Euler-tour dynamic trees: specialized balanced-tree structures support dynamic subtree maintenance in
O(log n)worst-case time even on adversarialn-deep chains, at the cost of heavy implementation complexity unnecessary for typical organizational depths.
Follow-up questions
- How would you implement a
move(person, new_manager)operation when an employee transfers to another manager? First walk upward fromnew_managerto verifypersonis neithernew_managernor an ancestor ofnew_manager(preventing cycles). Next, subtract1 + self.total[person]fromperson's previous manager and all previous ancestors, removepersonfrom the old manager'schildrencollection (using asetinstead of alistmakes detachmentO(1)rather thanO(direct_reports)), and finally linkpersonundernew_managerwhile adding1 + self.total[person]up the new ancestor chain inO(d_old + d_new)time. - How would you handle
remove(person)when someone departs the organization? Confirm the organizational policy first—most commonly,person's immediate subordinates are reassigned directly toperson's manager (or become top-level roots ifpersonhad no manager). Under that rule,person's ancestors lose just1total subordinate (becauseperson's team remains inside their subtree), each ofperson'skdirect subordinates hasself.managerupdated inO(k)time, andpersonis deleted from all three dictionaries inO(d + k)total time. - How would you persist and query these subtree counts in a relational SQL database rather than in memory? Storing only
edges(manager, report)requires a recursive CTE (a SQL query that repeatedly joins intermediate rows back toedgeslevel by level), costingO(subtree size)per lookup. To preserveO(1)reads in SQL, either maintain a materializedtotal_reportscolumn updated along theO(d)ancestor chain inside the same database transaction as each write, or maintain a closure table (an auxiliary table storing every(ancestor, descendant, depth)pair) where subtree size is a fast indexed lookup at the cost ofO(n * d)stored rows.
Follow-up questions
- How would you implement a `move(person, new_manager)` operation when an employee transfers to another manager?
- How would you handle `remove(person)` when someone departs the organization?
- How would you persist and query these subtree counts in a relational SQL database rather than in memory?
Similar questions
- Subordinate Rollups Across an Org Hierarchy
- 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