Company Hierarchy Operations: Organization Count, Depth Traversal, and Shared Supervisor

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

You are given a flat list of workforce records employees, where each element is a tuple (emp_id, title, reports_to):

  • emp_id (int): a unique integer identifier for the staff member.
  • title (str): the person's role name (multiple staff members may hold identical role names).
  • reports_to (Optional[int]): the emp_id of the person's immediate supervisor, or None if this person leads a standalone organization and has no supervisor.

Records in employees appear in arbitrary order, meaning a subordinate can appear earlier in the list than their supervisor. Build an OrgChart class initialized once from employees in O(n) time and implement three sets of queries over the hierarchy:

  1. Part 1 — Organization Count (count_orgs() -> int): An organization consists of one top-level leader (reports_to is None) together with everyone who reports up to that leader through one or more supervision links. Return how many separate organizations exist (0 when employees is empty).

  2. Part 2 — Depth-Grouped Listing (levels(), level_lines(), print_levels()): Group staff members by hierarchy depth across the entire workforce: depth 0 holds all top-level leaders, depth 1 holds everyone reporting directly to a depth-0 leader, depth 2 holds their direct reports, and so forth.

    • Within depth 0, list top-level leaders in the order they appear in employees.
    • Within any deeper level d >= 1, process supervisors in the exact order they appeared at depth d - 1, and for each supervisor list their direct reports in the order those reports appeared in employees.
    • levels() -> List[List[int]] returns the nested list of employee IDs per depth ([] if empty).
    • level_lines() -> List[str] formats each depth as comma-and-space separated entries "{emp_id} ({title})" ([] if empty).
    • print_levels() -> None prints each string from level_lines() on its own line.
  3. Part 3 — Deepest Shared Supervisor (first_common_manager(a: int, b: int) -> Optional[int]): Given two employee IDs a and b, return the lowest (deepest) employee in the hierarchy to whom both a and b report, directly or indirectly.

    • Nobody reports to themselves. Consequently, if a supervises b (directly or indirectly), a is excluded and the answer is a's own immediate supervisor; if a == b, the answer is a's immediate supervisor.
    • Return None whenever a or b is missing from employees, either employee is a top-level leader (reports_to is None), or the two employees belong to different organizations.

Examples

Example 1

Input:
employees = [
    (50, "Platform Eng", 25),
    (30, "Product Lead", 10),
    (70, "Advisory Chair", None),
    (25, "Infra Lead", 10),
    (10, "General Manager", None),
    (85, "Legal Counsel", 70),
    (60, "SRE", 50),
]

chart = OrgChart(employees)
chart.count_orgs()                    -> 2
chart.levels()                        -> [[70, 10], [85, 30, 25], [50], [60]]
chart.level_lines()                   -> [
    "70 (Advisory Chair), 10 (General Manager)",
    "85 (Legal Counsel), 30 (Product Lead), 25 (Infra Lead)",
    "50 (Platform Eng)",
    "60 (SRE)",
]
chart.first_common_manager(60, 30)    -> 10
chart.first_common_manager(25, 60)    -> 10
chart.first_common_manager(60, 85)    -> None

Explanation: - Two records (70 and 10, in that input order) have reports_to = None, forming 2 separate organizations. - Depth 0 is [70, 10]. Expanding 70 yields [85] and expanding 10 yields [30, 25] (preserving input order), giving depth 1 as [85, 30, 25]. Only 25 has a direct report (50) for depth 2, and 50 has direct report 60 for depth 3. - Employee 60 reports up through 50 -> 25 -> 10, while 30 reports directly to 10, so their deepest shared supervisor is 10. For (25, 60), 25 supervises 60 and does not report to itself, so both share 25's supervisor 10. Employees 60 and 85 belong to separate organizations (10 vs. 70), returning None.

Example 2

Input:
employees = [
    (12, "QA Specialist", 8),
    (4, "Studio Head", None),
    (15, "QA Specialist", 8),
    (8, "Delivery Lead", 4),
]

chart = OrgChart(employees)
chart.count_orgs()                    -> 1
chart.levels()                        -> [[4], [8], [12, 15]]
chart.level_lines()                   -> [
    "4 (Studio Head)",
    "8 (Delivery Lead)",
    "12 (QA Specialist), 15 (QA Specialist)",
]
chart.first_common_manager(12, 15)    -> 8
chart.first_common_manager(12, 12)    -> 8
chart.first_common_manager(12, 999)   -> None

Explanation: Even though 12 and 15 appear before their supervisor 8, two-pass initialization groups both under 8 in input order [12, 15]. Both 12 and 15 report directly to 8, querying (12, 12) returns 12's immediate supervisor 8, and 999 is an unknown ID so (12, 999) returns None.

Constraints

  • 0 <= len(employees) <= 30,000
  • Every emp_id in employees is unique.
  • Every non-None reports_to value matches an emp_id present in employees.
  • Supervision links are acyclic (the reporting graph forms a valid forest of rooted trees), and hierarchies may be up to 30,000 levels deep, so solutions must avoid recursion-depth limits.
  • OrgChart.__init__, count_orgs, levels, and level_lines should run in O(n) time and O(n) space; first_common_manager should run in O(h) time and O(1) auxiliary space per query, where h is the hierarchy height.

Step-by-step walkthrough

  1. Model the workforce tuples as a forest of rooted trees

    Each record (emp_id, title, reports_to) stores a single upward link from a staff member to their immediate supervisor. Anyone with reports_to = None sits at the root of an independent organization. Because multiple top-level leaders can exist side by side, the workforce forms a forest: a collection of disjoint trees where every non-root node has one parent and cycles do not occur.

    Visualize Example 1 as two trees side by side:

    Depth 0 (leaders)    70 (Advisory Chair)        10 (General Manager)
                                 |                     /            \
    Depth 1              85 (Legal Counsel)   30 (Product Lead)   25 (Infra Lead)
                                                                         |
    Depth 2                                                       50 (Platform Eng)
                                                                         |
    Depth 3                                                           60 (SRE)
    

    Because all three query parts inspect the same hierarchy, preprocess the flat tuple list once inside OrgChart.__init__ in O(n) time. State the boundary rules up front:

    • Input guarantees (plus a defensive loop check): Employee IDs are unique, non-None supervisor IDs exist in employees, and supervision chains are acyclic (though adding an O(1)-cost step counter when climbing upward guards against bad data cleanly).
    • Part 2 ordering rule: Staff members at the same depth across all organizations share a depth list. Depth 0 preserves original input order ([70, 10]), and each deeper layer visits supervisors in the previous layer's order while listing each supervisor's direct reports in input order.
    • Part 3 strict reporting rule: Nobody reports to themselves. If 25 supervises 60 (through 50), 25 cannot be the shared supervisor—the answer is 25's supervisor 10; likewise (50, 50) returns 25. Top-level leaders, missing IDs, and pairs from separate organizations return None.
  2. Build upward and downward maps in two linear passes

    Part 3 climbs upward (employee -> supervisor), whereas Part 2 expands downward (supervisor -> direct reports). Notice the ordering trap in Example 1: (50, "Platform Eng", 25) appears before (25, "Infra Lead", 10), and both appear before (10, "General Manager", None)!

    Appending 50 into self.reports[25] during a single naive pass over plain dictionaries would raise KeyError because 25 has not been registered yet. Splitting initialization into two O(n) passes handles arbitrary input order cleanly:

    1. Pass 1 records input order in self.order, stores self.title and self.manager, and creates an empty list self.reports[emp_id] = [] for every employee.
    2. Pass 2 iterates over self.order and appends each employee to self.reports[boss_id], preserving exact input order within every supervisor's direct-reports list.
    from typing import Dict, List, Optional, Tuple
    
    Employee = Tuple[int, str, Optional[int]]  # (id, title, reports_to)
    
    
    class OrgChart:
        def __init__(self, employees: List[Employee]) -> None:
            # self.order: employee IDs in original input order, e.g. [50, 30, 70, ...]
            self.order: List[int] = []
            # self.title: emp_id -> job title, e.g. {10: "General Manager", 50: "Platform Eng"}
            self.title: Dict[int, str] = {}
            # self.manager: emp_id -> direct manager ID (None for an org head)
            self.manager: Dict[int, Optional[int]] = {}
            # self.reports: manager_id -> direct report IDs in input order, e.g. {10: [30, 25]}
            self.reports: Dict[int, List[int]] = {}
    
            # Pass 1: Register every employee and initialize an empty direct-reports list
            for emp_id, job_title, reports_to in employees:
                self.order.append(emp_id)
                self.title[emp_id] = job_title
                self.manager[emp_id] = reports_to
                self.reports[emp_id] = []
    
            # Pass 2: Populate direct-reports lists (safe even when a report appeared before its manager)
            for emp_id in self.order:
                boss_id = self.manager[emp_id]
                if boss_id is not None and boss_id in self.reports:
                    self.reports[boss_id].append(emp_id)
    
  3. Part 1: count organizations by counting top-level leaders

    When every non-None supervisor ID is valid and no cycles exist, climbing upward from any staff member must reach a unique leader whose reports_to is None. Two leaders can never share subordinates because every record holds at most one reports_to ID. Consequently, each organization corresponds to exactly one None supervisor link, so we can count organizations in one linear scan without traversing trees!

    What would change if input data could be malformed? - If a record referenced an unlisted supervisor ID (say 999) or if two records pointed to each other (25 -> 50 -> 25), neither component would contain a None pointer—counting None entries would skip them, whereas graph connected-components / union-find would flag them as extra leaderless components.

    def heads(self) -> List[int]:
        """Return employee IDs whose reports_to is None, preserving input order."""
        head_ids: List[int] = []
        for emp_id in self.order:
            if self.manager[emp_id] is None:
                head_ids.append(emp_id)
        return head_ids
    
    
    def count_orgs(self) -> int:
        """Return the number of orgs (on valid input, each org has exactly one head)."""
        return len(self.heads())
    
  4. Part 2: group by depth with iterative breadth-first search

    Exploring a hierarchy one depth layer at a time—depth 0, then depth 1, then depth 2—is breadth-first search (BFS). Using two plain lists (current_level and next_level) keeps depth boundaries crisp without needing tuple tags or queue-length bookkeeping:

    1. Initialize current_level = self.heads().
    2. While current_level is non-empty, append it to all_levels, gather all direct reports of each supervisor in current_level into next_level, and set current_level = next_level.

    Trace Example 1 (self.reports = {70: [85], 10: [30, 25], 25: [50], 50: [60]}):

    Iteration   current_level   Direct reports gathered -> next_level    Formatted line
    ---------   -------------   --------------------------------------   -------------------------------------------------------
    1 (d = 0)   [70, 10]        70->[85]; 10->[30, 25] -> [85, 30, 25]   "70 (Advisory Chair), 10 (General Manager)"
    2 (d = 1)   [85, 30, 25]    85->[]; 30->[]; 25->[50] -> [50]         "85 (Legal Counsel), 30 (Product Lead), 25 (Infra Lead)"
    3 (d = 2)   [50]            50->[60]                 -> [60]         "50 (Platform Eng)"
    4 (d = 3)   [60]            60->[]                   -> []           "60 (SRE)"
    5           []              loop ends
    

    Because this loop is purely iterative, even a 30,000-person single-file chain completes in O(n) time without hitting Python's call-stack limit:

    def levels(self) -> List[List[int]]:
        """Return employee IDs grouped by depth across all orgs using iterative BFS."""
        all_levels: List[List[int]] = []
        current_level = self.heads()
    
        # Expand one full depth layer per iteration so level boundaries stay exact
        while current_level:
            all_levels.append(current_level)
            next_level: List[int] = []
            for manager_id in current_level:
                for report_id in self.reports[manager_id]:
                    next_level.append(report_id)
            current_level = next_level
        return all_levels
    
    
    def level_lines(self) -> List[str]:
        """Format each depth level as '70 (Advisory Chair), 10 (General Manager)'."""
        lines: List[str] = []
        for level in self.levels():
            formatted_entries: List[str] = []
            for emp_id in level:
                formatted_entries.append(f"{emp_id} ({self.title[emp_id]})")
            lines.append(", ".join(formatted_entries))
        return lines
    
    
    def print_levels(self) -> None:
        for line in self.level_lines():
            print(line)
    
  5. Part 3: align depths and climb upward in lockstep

    Finding the deepest shared supervisor is a lowest common ancestor (LCA) query on a forest with parent pointers.

    Because nobody reports to themselves, any valid shared supervisor of a and b must sit at or above manager_a = self.manager[a] and at or above manager_b = self.manager[b]. Stepping one link above a and b right at the start (and returning None immediately if either ID is unknown or is already a top-level leader) reduces every case—siblings, supervisor-subordinate pairs, and identical IDs—to one subproblem: find the deepest node where two upward chains converge.

    If the two starting supervisors sit at different depths, stepping both upward simultaneously would cause them to pass through their shared supervisor on different iterations and miss each other. Equalizing their depths first solves the query in O(h) time and O(1) extra memory:

    Goal on Example 1: first_common_manager(60, 30)
      manager_a = manager[60] = 50 (depth 2)
      manager_b = manager[30] = 10 (depth 0)
    
    Phase 1 (align depths): lift cur_x twice (50 -> 25 -> 10) until depth_x == depth_y == 0
    Phase 2 (lockstep):     cur_x == 10 and cur_y == 10 -> already equal! Return 10.
    
    def first_common_manager(self, a: int, b: int) -> Optional[int]:
        if a not in self.manager or b not in self.manager:
            return None
    
        # Start one step above a and b because nobody reports to themselves
        manager_a = self.manager[a]
        manager_b = self.manager[b]
        if manager_a is None or manager_b is None:
            return None
        return self._meet(manager_a, manager_b)
    
    
    def _depth(self, emp_id: int) -> int:
        """Count how many managers sit above emp_id (an org head has depth 0)."""
        depth = 0
        boss_id = self.manager.get(emp_id)
        while boss_id is not None:
            depth += 1
            # Guard against malformed cyclic input: a valid chain has at most n - 1 edges
            if depth > len(self.manager):
                raise ValueError(f"reporting cycle above employee {emp_id}")
            boss_id = self.manager.get(boss_id)
        return depth
    
    
    def _meet(self, start_x: int, start_y: int) -> Optional[int]:
        """Find the deepest employee at or above both start_x and start_y (or None)."""
        depth_x = self._depth(start_x)
        depth_y = self._depth(start_y)
    
        cur_x: Optional[int] = start_x
        cur_y: Optional[int] = start_y
    
        # Phase 1: Lift whichever node is deeper until both sit at the exact same depth
        while depth_x > depth_y and cur_x is not None:
            cur_x = self.manager.get(cur_x)
            depth_x -= 1
        while depth_y > depth_x and cur_y is not None:
            cur_y = self.manager.get(cur_y)
            depth_y -= 1
    
        # Phase 2: Step both upward in lockstep until they meet (or both hit None together)
        while cur_x != cur_y:
            cur_x = self.manager.get(cur_x) if cur_x is not None else None
            cur_y = self.manager.get(cur_y) if cur_y is not None else None
        return cur_x
    
  6. Trace Part 3 across same-org, ancestor, and cross-org queries

    In Example 1, node depths are 70, 10 -> 0; 85, 30, 25 -> 1; 50 -> 2; 60 -> 3. Trace five representative calls:

    Query      Initial (cur_x, cur_y) & depths   After depth alignment   Lockstep climb       Result
    ---------  --------------------------------  ----------------------  -------------------  ------
    (60, 30)   (50 [d=2], 10 [d=0])              lift 50->25->10:(10,10) already equal        10
    (25, 60)   (10 [d=0], 50 [d=2])              lift 50->25->10:(10,10) already equal        10
    (50, 50)   (25 [d=1], 25 [d=1])              (25, 25)                already equal        25
    (60, 85)   (50 [d=2], 70 [d=0])              lift 50->25->10:(10,70) step -> (None, None) None
    (10, 60)   manager[10] is None               early exit              -                    None
    

    Look at (60, 85) across two different organizations: once Phase 1 aligns cur_x = 10 and cur_y = 70 at depth 0, one lockstep step moves both pointers to None together, terminating the loop cleanly with None.

  7. Complete Python solution

    Combining two-pass setup with Parts 1, 2, and 3 yields the complete solution.py:

    from typing import Dict, List, Optional, Tuple
    
    Employee = Tuple[int, str, Optional[int]]  # (id, title, reports_to)
    
    
    class OrgChart:
        """An org chart built once from (id, title, reports_to) tuples.
    
        The input may list an employee before their manager. It is assumed valid:
        unique IDs, every non-None reports_to is a listed ID, and no cycles.
        """
    
        def __init__(self, employees: List[Employee]) -> None:
            # self.order: employee IDs in original input order, e.g. [50, 30, 70, ...]
            self.order: List[int] = []
            # self.title: emp_id -> job title, e.g. {10: "General Manager", 50: "Platform Eng"}
            self.title: Dict[int, str] = {}
            # self.manager: emp_id -> direct manager ID (None for an org head)
            self.manager: Dict[int, Optional[int]] = {}
            # self.reports: manager_id -> direct report IDs in input order, e.g. {10: [30, 25]}
            self.reports: Dict[int, List[int]] = {}
    
            # Pass 1: Register every employee and initialize an empty direct-reports list
            for emp_id, job_title, reports_to in employees:
                self.order.append(emp_id)
                self.title[emp_id] = job_title
                self.manager[emp_id] = reports_to
                self.reports[emp_id] = []
    
            # Pass 2: Populate direct-reports lists (safe even when a report appeared before its manager)
            for emp_id in self.order:
                boss_id = self.manager[emp_id]
                if boss_id is not None and boss_id in self.reports:
                    self.reports[boss_id].append(emp_id)
    
        # ----- Part 1 -----
    
        def heads(self) -> List[int]:
            """Return employee IDs whose reports_to is None, preserving input order."""
            head_ids: List[int] = []
            for emp_id in self.order:
                if self.manager[emp_id] is None:
                    head_ids.append(emp_id)
            return head_ids
    
        def count_orgs(self) -> int:
            """Return the number of orgs (on valid input, each org has exactly one head)."""
            return len(self.heads())
    
        # ----- Part 2 -----
    
        def levels(self) -> List[List[int]]:
            """Return employee IDs grouped by depth across all orgs using iterative BFS."""
            all_levels: List[List[int]] = []
            current_level = self.heads()
    
            # Expand one full depth layer per iteration so level boundaries stay exact
            while current_level:
                all_levels.append(current_level)
                next_level: List[int] = []
                for manager_id in current_level:
                    for report_id in self.reports[manager_id]:
                        next_level.append(report_id)
                current_level = next_level
            return all_levels
    
        def level_lines(self) -> List[str]:
            """Format each depth level as '70 (Advisory Chair), 10 (General Manager)'."""
            lines: List[str] = []
            for level in self.levels():
                formatted_entries: List[str] = []
                for emp_id in level:
                    formatted_entries.append(f"{emp_id} ({self.title[emp_id]})")
                lines.append(", ".join(formatted_entries))
            return lines
    
        def print_levels(self) -> None:
            for line in self.level_lines():
                print(line)
    
        # ----- Part 3 -----
    
        def first_common_manager(self, a: int, b: int) -> Optional[int]:
            """Lowest employee whom both a and b report to, directly or indirectly.
    
            Nobody reports to themselves, so if a manages b the answer is a's own manager,
            and for a == b it is their direct manager. Return None for an unknown ID, a head,
            or two employees in different orgs.
            """
            if a not in self.manager or b not in self.manager:
                return None
    
            # Start one step above a and b because nobody reports to themselves
            manager_a = self.manager[a]
            manager_b = self.manager[b]
            if manager_a is None or manager_b is None:
                return None
            return self._meet(manager_a, manager_b)
    
        def _depth(self, emp_id: int) -> int:
            """Count how many managers sit above emp_id (an org head has depth 0)."""
            depth = 0
            boss_id = self.manager.get(emp_id)
            while boss_id is not None:
                depth += 1
                # Guard against malformed cyclic input: a valid chain has at most n - 1 edges
                if depth > len(self.manager):
                    raise ValueError(f"reporting cycle above employee {emp_id}")
                boss_id = self.manager.get(boss_id)
            return depth
    
        def _meet(self, start_x: int, start_y: int) -> Optional[int]:
            """Find the deepest employee at or above both start_x and start_y (or None)."""
            depth_x = self._depth(start_x)
            depth_y = self._depth(start_y)
    
            cur_x: Optional[int] = start_x
            cur_y: Optional[int] = start_y
    
            # Phase 1: Lift whichever node is deeper until both sit at the exact same depth
            while depth_x > depth_y and cur_x is not None:
                cur_x = self.manager.get(cur_x)
                depth_x -= 1
            while depth_y > depth_x and cur_y is not None:
                cur_y = self.manager.get(cur_y)
                depth_y -= 1
    
            # Phase 2: Step both upward in lockstep until they meet (or both hit None together)
            while cur_x != cur_y:
                cur_x = self.manager.get(cur_x) if cur_x is not None else None
                cur_y = self.manager.get(cur_y) if cur_y is not None else None
            return cur_x
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of each (emp_id, title, reports_to) tuple like an ID card that only lists the person's immediate supervisor. Climbing up the supervision chain is effortless with those cards, whereas listing the workforce downward by depth requires inverting those links into a supervisor-to-direct-reports directory first. Across the whole workforce, top-level leaders (reports_to is None) act as roots of a forest—a set of separate hierarchy trees.

Without building that directory cleanly, straightforward attempts hit three classic snags. Re-scanning the raw tuple list for every depth layer turns an O(n) traversal into O(n^2); populating direct-report lists in a single pass over plain dictionaries crashes with KeyError whenever a subordinate appears earlier in employees than their supervisor; and climbing upward from two employees simultaneously without matching their depths first makes the two pointers step past their shared supervisor on different iterations.

Trace a five-person slice of Example 1 [(50, "Platform Eng", 25), (30, "Product Lead", 10), (25, "Infra Lead", 10), (10, "General Manager", None), (60, "SRE", 50)]:

  1. Two-pass initialization: Pass 1 records manager = {50: 25, 30: 10, 25: 10, 10: None, 60: 50} and empty report buckets; Pass 2 populates reports = {10: [30, 25], 25: [50], 50: [60], 30: [], 60: []} safely even though 50 appeared before 25 and 25 before 10.
  2. Part 1 (count_orgs): Only 10 has manager[10] is None, giving 1 organization (and 2 on full Example 1 once 70 is included).
  3. Part 2 (levels): Iterative breadth-first search (BFS) (visiting nodes one depth layer at a time from the roots) expands [10] -> [30, 25] -> [50] -> [60].
  4. Part 3 (first_common_manager(60, 30)): Stepping one link above each employee gives cur_x = 50 (depth 2) and cur_y = 10 (depth 0). Lifting cur_x twice (50 -> 25 -> 10) aligns both pointers at depth 0 where cur_x == cur_y == 10, returning 10.

Complexity

  • OrgChart.__init__: O(n) time and O(n) space, where n is len(employees). We make two linear passes over n records performing O(1) dictionary reads and list appends, storing each employee ID once in order, title, manager, and at most one supervisor's reports list.
  • Part 1 (count_orgs): O(n) time and O(n) space (or O(1) extra space if counting None managers directly without materializing heads()), scanning self.order once.
  • Part 2 (levels / level_lines / print_levels): O(n) time and O(n) space. Every employee has at most one supervisor, so each ID enters next_level once and is formatted into a string once.
  • Part 3 (first_common_manager): O(h) time and O(1) extra space per query, where h is the height of the deepest tree (h <= n - 1). Measuring both depths and climbing upward in two phases performs at most 4 * h dictionary lookups without allocating any per-query set or list.

Edge cases

  • Empty input ([]): count_orgs() returns 0, levels() and level_lines() return [], and first_common_manager returns None.
  • Subordinates listed ahead of supervisors: Handled seamlessly by the two-pass constructor because Pass 1 initializes self.reports[emp_id] for every employee before Pass 2 appends direct reports.
  • Supervisor-subordinate pair ((25, 60)): Because nobody reports to themselves, 25 reports to 10 and 60 reports through 50 -> 25 -> 10, so first_common_manager(25, 60) returns 10 (while (10, 60) returns None since leader 10 has no supervisor).
  • Same employee queried twice ((50, 50)): Starting at manager[50] on both sides immediately returns 50's direct supervisor 25 (or None for a top-level leader like (70, 70)).
  • Separate organizations ((60, 85)): Depth alignment brings the pointers to 10 and 70 at depth 0, and one lockstep step advances both to None simultaneously, returning None.
  • Pathologically deep chains (30,000 levels): Every traversal and depth lookup uses iterative for/while loops, avoiding Python's RecursionError frame limit.

Common mistakes

  • Populating self.reports in a single pass with plain dicts: Executing self.reports[reports_to].append(emp_id) in one pass raises KeyError whenever a direct report precedes their supervisor in employees.
  • Losing depth boundaries in BFS: Dumping nodes into one flat queue without tracking layer boundaries merges all depths onto a single output line.
  • Using recursion for tree walks or depth calculation: Recursive helpers raise RecursionError on chains deeper than ~1,000 employees.
  • Rebuilding lookup maps inside first_common_manager: Constructing emp_id -> manager inside each Part 3 call slows every query from O(h) down to O(n).
  • Stepping upward in lockstep before equalizing depths: If one pointer starts at depth 2 and the other at depth 0, moving both together makes them pass through their common supervisor on different steps and miss each other.
  • Forgetting to clarify self-reporting semantics in Part 3: Returning 25 vs. 10 for first_common_manager(25, 50) is the standard lowest common ancestor (LCA) convention question—confirm whether an employee counts as their own supervisor before coding.

Alternative approaches

  • Visited-ancestors hash set for Part 3: Climb upward from manager[a] storing every visited supervisor in a set, then climb upward from manager[b] and return the first ID present in that set. Time stays O(h) with slightly shorter code, trading O(h) temporary memory per query for brevity.
  • collections.defaultdict(list) in __init__: Allows single-pass population of self.reports, though two passes with plain dictionaries make validating that reports_to exists in employees trivial.
  • Sorted IDs per depth: If an interviewer prefers ascending numeric IDs on each line instead of manager-grouped input order, sort each current_level in O(n log n) total time.

Follow-up questions

  • Suppose first_common_manager runs hundreds of thousands of times against an unchanging hierarchy. What data structures would you precompute to accelerate each lookup? Record each employee's depth once during levels() in O(n) time, and precompute a binary lifting table up[k][emp]—a 2D table storing each employee's 2^k-th supervisor (1st, 2nd, 4th, 8th, ...) in O(n log n) time and space. A query then jumps the deeper pointer upward using the binary bits of depth_x - depth_y and lifts both pointers together by decreasing powers of two whenever up[k][x] != up[k][y], guaranteeing O(log n) worst-case time per query (~15 lookups for n = 30,000), or O(1) query time via an Euler tour (flattening a tree walk into a depth array) paired with a sparse-table range-minimum structure.

  • If input validation is required, how can you detect circular supervision chains and output the exact members participating in each loop? Climb upward from every unvisited employee using three-state coloring (unvisited, "visiting" for nodes on the active climb, and "checked" for nodes already proven loop-free). When a climb hits None, an unknown ID, or a "checked" node, mark the entire current path "checked"; if it encounters a "visiting" node u, slice the active path from u onward to capture that exact cycle once before marking the path "checked"—running in O(n) total time and space:

python def find_cycles(employees): manager = {emp_id: boss for emp_id, _, boss in employees} state = {} # emp_id -> "visiting" (active chain) or "checked" (verified) cycles = [] for start in manager: path = [] node = start while node is not None and node in manager and node not in state: state[node] = "visiting" path.append(node) node = manager[node] if node is not None and state.get(node) == "visiting": cycles.append(path[path.index(node):]) for visited in path: state[visited] = "checked" return cycles

  • How would you expand Part 1 so that, for every independent organization, it reports both total headcount and maximum hierarchy height? Run the same iterative two-list BFS starting from one single-element root list [head] at a time, accumulating headcount += len(current_level) and height += 1 until current_level becomes empty. Because every staff member belongs to exactly one leader's tree, summing across all leaders visits each employee once in O(n) total time and returns {70: (2, 2), 10: (5, 4)} on Example 1.

  • How would you generalize Part 3 to compute the deepest shared supervisor across an arbitrary list of k >= 2 employee IDs? Fold the pairwise _meet helper across the group: initialize shared = chart.manager[group[0]], and for each subsequent emp in group[1:], update shared = chart._meet(shared, chart.manager[emp]), returning None immediately if any ID is missing, is a top-level leader, or causes shared to become None. Because every supervisor shared by x and y is at or above _meet(x, y), pairwise meeting is associative (independent of grouping order) and runs in O(k * h) time and O(1) extra space.

Follow-up questions

Similar questions

More Merge interview questions

All 2 Merge questions →