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]): theemp_idof the person's immediate supervisor, orNoneif 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:
-
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 (0whenemployeesis empty). -
Part 2 — Depth-Grouped Listing (
levels(),level_lines(),print_levels()): Group staff members by hierarchy depth across the entire workforce: depth0holds all top-level leaders, depth1holds everyone reporting directly to a depth-0leader, depth2holds their direct reports, and so forth.- Within depth
0, list top-level leaders in the order they appear inemployees. - Within any deeper level
d >= 1, process supervisors in the exact order they appeared at depthd - 1, and for each supervisor list their direct reports in the order those reports appeared inemployees. 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() -> Noneprints each string fromlevel_lines()on its own line.
- Within depth
-
Part 3 — Deepest Shared Supervisor (
first_common_manager(a: int, b: int) -> Optional[int]): Given two employee IDsaandb, return the lowest (deepest) employee in the hierarchy to whom bothaandbreport, directly or indirectly.- Nobody reports to themselves. Consequently, if
asupervisesb(directly or indirectly),ais excluded and the answer isa's own immediate supervisor; ifa == b, the answer isa's immediate supervisor. - Return
Nonewheneveraorbis missing fromemployees, either employee is a top-level leader (reports_to is None), or the two employees belong to different organizations.
- Nobody reports to themselves. Consequently, if
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_idinemployeesis unique. - Every non-
Nonereports_tovalue matches anemp_idpresent inemployees. - Supervision links are acyclic (the reporting graph forms a valid forest of rooted trees), and hierarchies may be up to
30,000levels deep, so solutions must avoid recursion-depth limits. OrgChart.__init__,count_orgs,levels, andlevel_linesshould run inO(n)time andO(n)space;first_common_managershould run inO(h)time andO(1)auxiliary space per query, wherehis the hierarchy height.
Step-by-step walkthrough
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 withreports_to = Nonesits 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-
Nonesupervisor IDs exist inemployees, 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
0preserves 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
25supervises60(through50),25cannot be the shared supervisor—the answer is25's supervisor10; likewise(50, 50)returns25. Top-level leaders, missing IDs, and pairs from separate organizations returnNone.
- Input guarantees (plus a defensive loop check): Employee IDs are unique, non-
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
50intoself.reports[25]during a single naive pass over plain dictionaries would raiseKeyErrorbecause25has not been registered yet. Splitting initialization into two O(n) passes handles arbitrary input order cleanly:- Pass 1 records input order in
self.order, storesself.titleandself.manager, and creates an empty listself.reports[emp_id] = []for every employee. - Pass 2 iterates over
self.orderand appends each employee toself.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)- Pass 1 records input order in
Part 1: count organizations by counting top-level leaders
When every non-
Nonesupervisor ID is valid and no cycles exist, climbing upward from any staff member must reach a unique leader whosereports_toisNone. Two leaders can never share subordinates because every record holds at most onereports_toID. Consequently, each organization corresponds to exactly oneNonesupervisor 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 aNonepointer—countingNoneentries 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())Part 2: group by depth with iterative breadth-first search
Exploring a hierarchy one depth layer at a time—depth
0, then depth1, then depth2—is breadth-first search (BFS). Using two plain lists (current_levelandnext_level) keeps depth boundaries crisp without needing tuple tags or queue-length bookkeeping:- Initialize
current_level = self.heads(). - While
current_levelis non-empty, append it toall_levels, gather all direct reports of each supervisor incurrent_levelintonext_level, and setcurrent_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 endsBecause 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)- Initialize
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
aandbmust sit at or abovemanager_a = self.manager[a]and at or abovemanager_b = self.manager[b]. Stepping one link aboveaandbright at the start (and returningNoneimmediately 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_xTrace 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 - NoneLook at
(60, 85)across two different organizations: once Phase 1 alignscur_x = 10andcur_y = 70at depth0, one lockstep step moves both pointers toNonetogether, terminating the loop cleanly withNone.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)]:
- Two-pass initialization: Pass 1 records
manager = {50: 25, 30: 10, 25: 10, 10: None, 60: 50}and empty report buckets; Pass 2 populatesreports = {10: [30, 25], 25: [50], 50: [60], 30: [], 60: []}safely even though50appeared before25and25before10. - Part 1 (
count_orgs): Only10hasmanager[10] is None, giving1organization (and2on full Example 1 once70is included). - 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]. - Part 3 (
first_common_manager(60, 30)): Stepping one link above each employee givescur_x = 50(depth 2) andcur_y = 10(depth 0). Liftingcur_xtwice (50 -> 25 -> 10) aligns both pointers at depth 0 wherecur_x == cur_y == 10, returning10.
Complexity
OrgChart.__init__: O(n) time and O(n) space, wherenislen(employees). We make two linear passes overnrecords performing O(1) dictionary reads and list appends, storing each employee ID once inorder,title,manager, and at most one supervisor'sreportslist.- Part 1 (
count_orgs): O(n) time and O(n) space (or O(1) extra space if countingNonemanagers directly without materializingheads()), scanningself.orderonce. - Part 2 (
levels/level_lines/print_levels): O(n) time and O(n) space. Every employee has at most one supervisor, so each ID entersnext_levelonce and is formatted into a string once. - Part 3 (
first_common_manager): O(h) time and O(1) extra space per query, wherehis the height of the deepest tree (h <= n - 1). Measuring both depths and climbing upward in two phases performs at most4 * hdictionary lookups without allocating any per-query set or list.
Edge cases
- Empty input (
[]):count_orgs()returns0,levels()andlevel_lines()return[], andfirst_common_managerreturnsNone. - 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,25reports to10and60reports through50 -> 25 -> 10, sofirst_common_manager(25, 60)returns10(while(10, 60)returnsNonesince leader10has no supervisor). - Same employee queried twice (
(50, 50)): Starting atmanager[50]on both sides immediately returns50's direct supervisor25(orNonefor a top-level leader like(70, 70)). - Separate organizations (
(60, 85)): Depth alignment brings the pointers to10and70at depth 0, and one lockstep step advances both toNonesimultaneously, returningNone. - Pathologically deep chains (
30,000levels): Every traversal and depth lookup uses iterativefor/whileloops, avoiding Python'sRecursionErrorframe limit.
Common mistakes
- Populating
self.reportsin a single pass with plain dicts: Executingself.reports[reports_to].append(emp_id)in one pass raisesKeyErrorwhenever a direct report precedes their supervisor inemployees. - 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
RecursionErroron chains deeper than ~1,000 employees. - Rebuilding lookup maps inside
first_common_manager: Constructingemp_id -> managerinside 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
25vs.10forfirst_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 aset, then climb upward frommanager[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 ofself.reports, though two passes with plain dictionaries make validating thatreports_toexists inemployeestrivial.- Sorted IDs per depth: If an interviewer prefers ascending numeric IDs on each line instead of manager-grouped input order, sort each
current_levelin 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
depthonce duringlevels()in O(n) time, and precompute a binary lifting tableup[k][emp]—a 2D table storing each employee's2^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 ofdepth_x - depth_yand lifts both pointers together by decreasing powers of two wheneverup[k][x] != up[k][y], guaranteeing O(log n) worst-case time per query (~15 lookups forn = 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 hitsNone, an unknown ID, or a"checked"node, mark the entire current path"checked"; if it encounters a"visiting"nodeu, slice the active path fromuonward 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, accumulatingheadcount += len(current_level)andheight += 1untilcurrent_levelbecomes 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
_meethelper across the group: initializeshared = chart.manager[group[0]], and for each subsequentempingroup[1:], updateshared = chart._meet(shared, chart.manager[emp]), returningNoneimmediately if any ID is missing, is a top-level leader, or causessharedto becomeNone. Because every supervisor shared byxandyis 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
- Suppose first_common_manager runs hundreds of thousands of times against an unchanging hierarchy. What data structures would you precompute to accelerate each lookup?
- If input validation is required, how can you detect circular supervision chains and output the exact members participating in each loop?
- How would you expand Part 1 so that, for every independent organization, it reports both total headcount and maximum hierarchy height?
- How would you generalize Part 3 to compute the deepest shared supervisor across an arbitrary list of k >= 2 employee IDs?
Similar questions
- Unified User Model and Mappers for Heterogeneous API Payloads
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager