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]]) -> None Constructs the hierarchy and precomputes any needed summary counts. Raises ValueError if any employee is assigned two managers or if pairs forms a cycle (including self-reporting).
  • look_up(name: str) -> Tuple[str, int, int] Returns (role, direct_report_count, total_report_count) in O(1) expected time:
    • role: "mgr" when name supervises at least 1 immediate subordinate, or "ic" otherwise.
    • direct_report_count: count of immediate subordinates reporting directly to name.
    • total_report_count: count of all direct and indirect subordinates anywhere beneath name (excluding name). Raises KeyError when name is not registered in the chart.
  • add(manager: str, report: str) -> None Attaches report as an immediate subordinate of manager, registering either name if unseen so far. When report is already a top-level leader with subordinates, report's entire subtree moves underneath manager. Raises ValueError—leaving all existing state untouched—if report already has a manager or if linking manager to report would close a cycle (including manager == 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 pairs is 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 n distinct employees: O(n) preprocessing time and O(n) space in __init__, O(1) expected time per look_up, and O(d) time per add where d is the number of ancestors above manager.

Step-by-step walkthrough

  1. 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 to name (their out-degree, or child count).
    • total_report_count: how many employees sit anywhere beneath name in their subtree (all descendants—direct subordinates, their subordinates, and so on—excluding name).
    • role: "mgr" when direct_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
       |
      Jude
    

    Good 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 if report is an existing top-level leader, their entire subtree moves underneath manager.
    • Invalid links—assigning a second manager, manager == report, or making an ancestor report to one of their own descendants—raise ValueError without changing any existing state.
  2. 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 from name on every look_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 total
    

    Why does this break down under heavy read traffic?

    • Constructing children takes O(n) time and O(n) space for n employees.
    • Each look_up(name) visits every descendant of name: O(1) on a leaf contributor, but O(n) on a company-wide executive.
    • With 100,000 employees and 100,000 directory queries hitting senior leaders, the service performs up to 100,000 * 100,000 = 10^10 node visits—recounting identical subtrees over and over.
  3. 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 child contributes 1 (for child themselves) plus total[child] (everyone beneath child):

    total[leaf]   = 0
    total[person] = sum over each child in children[person] of (1 + total[child])
    

    Evaluating total from 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 precomputing total across the entire forest takes O(n) time and O(n) extra space (one integer per employee).

    That directly addresses the complexity trade-off:

    1. Read-heavy optimization: compute total[person] once up front instead of walking subtrees during reads.
    2. Constant-time lookup: with self.children and self.total built in O(n) preprocessing time and O(n) space, look_up(name) simply reads len(self.children[name]) and self.total[name] in O(1) expected time.
  4. 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: maps report -> manager only for employees who have a manager. Top-level roots are simply the employees absent from self.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] = 0
    

    Because Phase 1 wires all edges before Phase 2 starts, pairs can arrive in any order—even when a subordinate's pair appears earlier than their manager's pair.

  5. Compute totals iteratively and detect cycles

    A recursive dfs(person) helper is tempting, but CPython's default call-stack limit is 1,000 frames: a deep vertical chain of 5,000 managers (emp0 -> emp1 -> ... -> emp4999) would crash with RecursionError.

    An explicit stack produces a clean bottom-up order in two passes:

    1. Push every root (name not in self.manager) onto stack, pop person, append person to order, and push person's children. Because children are pushed after their manager is popped, every manager precedes all of their descendants in order.
    2. 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 (Kira and Leo both have a manager) and is never reached from stack. Therefore len(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
    
  6. Answer look_up in O(1) time

    With self.children and self.total ready, look_up performs zero traversal: Python lists store their length directly (O(1)), and self.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])
    
  7. 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 manager and the ancestor chain above manager change, and each one increases by gained_reports = 1 + self.total[report] (1 for report plus everyone already in report's subtree).

    Validate before mutating any dictionary so a rejected add never leaves partial edits behind:

    1. report must not already have a manager (report not in self.manager).
    2. Walking upward from manager via self.manager must never encounter report (catching both manager == report and manager sitting inside report'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)
    

    add walks the ancestor chain twice (once to check for cycles, once to add gained_reports), taking O(d) time where d is manager's depth (~5–12 hops in typical companies, O(n) worst case on a single chain), while preserving O(1) look_up.

  8. 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!
    
  9. 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"]]:

  1. Wire links: "Dana" supervises ["Eli", "Faye"], "Eli" supervises ["Hana"], and "Faye" and "Hana" supervise []. Only "Dana" lacks a manager, making "Dana" the root.
  2. Bottom-up pass (Hana, Faye, Eli, Dana): total["Hana"] = 0 and total["Faye"] = 0; next total["Eli"] = 1 + total["Hana"] = 1; finally total["Dana"] = (1 + total["Eli"]) + (1 + total["Faye"]) = 2 + 1 = 3.
  3. Instant lookup: look_up("Dana") reads len(children["Dana"]) = 2 and total["Dana"] = 3, returning ("mgr", 2, 3) in O(1) time.
  4. Dynamic add("Faye", "Zoe"): gained_reports = 1 + 0 = 1; walking upward Faye -> Dana updates total["Faye"] from 0 to 1 ("Faye" flips to "mgr") and total["Dana"] from 3 to 4, 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), n employees have at most n - 1 reporting links. We scan pairs once 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, and self.total hold at most n keys each, and all children lists combined store at most n - 1 string references. The temporary stack and order lists during setup also hold n names.
  • look_up time — O(1) expected: checking membership in self.children, reading Python's cached list length (len(...)), and reading self.total[name] require two hash-map lookups plus one integer read (treating short string hashing as O(1)).
  • add time — O(d): we walk upward along self.manager from manager to its root once to confirm report is not an ancestor (blocking cycles), then walk the same d ancestors once more to add 1 + self.total[report].

Edge cases

  • Empty chart (pairs = []): initializes cleanly so any look_up raises KeyError, while a subsequent add("Kira", "Leo") registers both employees.
  • Leaf contributors and multiple roots: employees appearing only as report get children[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,000 levels): driving traversal with an explicit Python stack list rather than recursive calls avoids CPython's ~1,000-frame RecursionError.
  • Merging an existing team via add: attaching top-level leader "Mina" (who already supervises 2 people) under "Leo" adds 1 + 2 = 3—not 1—to "Leo" and every ancestor above "Leo".
  • Rejected updates leave state untouched: duplicate managers, self-loops (add("Kira", "Kira") or add("Fresh", "Fresh")), and ancestor loops (add("Zoe", "Kira")) raise ValueError before _ensure mutates any dictionary.

Common mistakes

  • Counting name themselves inside total_report_count (off-by-one) or returning only immediate subordinates instead of the full subtree.
  • Forgetting to add report to self.children when they supervise nobody, causing look_up on leaf contributors to raise KeyError.
  • Using recursive post-order DFS, which passes shallow examples of height 4 but crashes with RecursionError on skewed chains of 1,500+ employees.
  • Incrementing ancestors by +1 instead of 1 + self.total[report] inside add, undercounting whenever an existing leader brings a team along.
  • Updating only the immediate manager in add while forgetting higher-level ancestors—or rerunning an O(n) full-chart pass on every single add.
  • Calling _ensure or mutating self.children before validating cycles, leaving phantom employees behind after raising ValueError.

Alternative approaches

  • Lazy memoization on read: compute total[name] via DFS on first query and cache it. Each add still has to invalidate O(d) ancestors, and the next query on a root drops back to O(n)—making eager updates simpler and consistently O(1) on reads.
  • Dirty flag for bulk writes: if thousands of add operations arrive in a batch with zero reads in between, add can validate and flip dirty = True, deferring one O(n) _compute_totals() pass until the next look_up (O(n + k) for k writes rather than O(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 adversarial n-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 from new_manager to verify person is neither new_manager nor an ancestor of new_manager (preventing cycles). Next, subtract 1 + self.total[person] from person's previous manager and all previous ancestors, remove person from the old manager's children collection (using a set instead of a list makes detachment O(1) rather than O(direct_reports)), and finally link person under new_manager while adding 1 + self.total[person] up the new ancestor chain in O(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 to person's manager (or become top-level roots if person had no manager). Under that rule, person's ancestors lose just 1 total subordinate (because person's team remains inside their subtree), each of person's k direct subordinates has self.manager updated in O(k) time, and person is deleted from all three dictionaries in O(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 to edges level by level), costing O(subtree size) per lookup. To preserve O(1) reads in SQL, either maintain a materialized total_reports column updated along the O(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 of O(n * d) stored rows.

Follow-up questions

Similar questions

More Patreon interview questions

All 3 Patreon questions →