Shared Manager in Organizational Hierarchy
Trees & GraphsAuto-graded · 28 test casesLast updated
Tests tree traversal, ancestor queries, and handling multiple input formats with a custom precedence rule.
You are building an organizational chart tool that finds the shared manager between two employees.
Write a function that accepts two different representations of an organizational hierarchy and returns the appropriate manager according to specific rules.
Input Formats
Your function receives a mode parameter that determines how the hierarchy is encoded:
Mode "children": The tree parameter is a list where tree[i] contains the list of employee IDs who report directly to employee i. Employee IDs range from 0 to n-1. The root parameter indicates the top of the hierarchy (or None, in which case you should identify the root as the employee with no manager).
Mode "parent": The tree parameter is a list where tree[i] is the ID of the manager of employee i. A value of -1 indicates the employee has no manager (is a root). The root parameter is provided but may be ignored in this mode.
Return Rules
Given two employees a and b:
- If neither employee is an ancestor of the other in the reporting chain, return their lowest common ancestor (the deepest employee who is an ancestor of both).
- If one employee reports up through the other (including when
a == b), return the parent of that common ancestor instead of the ancestor itself. - Return
Noneif no valid manager exists: when employees belong to separate organizational trees, when either employee ID is invalid, or when the rule would require returning the parent of a root node.
Constraints
1 ≤ n ≤ 10,000wherenis the number of employees0 ≤ a, b < nfor valid queries- Employee IDs are non-negative integers
- The hierarchy forms a valid forest (one or more trees with no cycles)
- Tree height may reach
nin degenerate cases
Examples
Example 1
Input: shared_manager('children', [[1, 2], [3, 4], [5], [], [], []], 0, 3, 4)
Output: 1
Example 2
Input: shared_manager('children', [[1, 2], [3, 4], [5], [], [], []], 0, 1, 3)
Output: 0
Example 3
Input: shared_manager('parent', [-1, 0, 0, 1, 1, 2], None, 4, 5)
Output: 0
Example 4
Input: shared_manager('children', [[1, 2], [3, 4], [5], [], [], []], 0, 0, 5)
Output: None
Hints
Hint 1
Convert both input formats to a unified representation before solving the core problem.
Hint 2
The classic depth-alignment algorithm works well: find each node's depth, align to the same level, then climb together until they meet.
Hint 3
Handle the special ancestor case by checking whether the LCA equals one of the input nodes, then returning its parent.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem presents two different ways to encode the same organizational structure. The cleanest solution converts both formats into a single representation—a parent array—then solves the lowest common ancestor (LCA) problem with a special rule.
Step 1: Normalize to Parent Array
- "parent" mode already provides a parent array; copy it directly.
- "children" mode provides adjacency lists. Iterate through each employee and their direct reports, setting
par[report] = managerfor each relationship. Employees with no entry remain at-1, indicating they are roots.
This unification lets us handle both modes with one algorithm.
Step 2: Compute Depths
Walk from each unvisited employee up to a root (or to an already-visited ancestor), recording the path. Once we reach a node with known depth or hit -1, assign depths back down the recorded path. This iterative memoized approach visits each node exactly once, taking O(n) time and avoiding Python's recursion depth limits on tall hierarchies.
Step 3: Verify Same Tree
Climb from each employee to their root. If the roots differ, the employees belong to separate organizations and share no manager; return None.
Step 4: Find the LCA
Use the classic depth-alignment algorithm:
- Lift the deeper employee until both are at the same depth.
- Climb both in lockstep until they meet.
The meeting point is the lowest common ancestor.
Step 5: Apply the Special Rule
If the LCA equals a or b, one employee is an ancestor of the other. The rule requires returning the ancestor's manager (its parent) instead. If that ancestor is a root (par[x] == -1), no manager exists, so return None. Otherwise, return the LCA.
Why It Works
- Depth alignment ensures both pointers represent ancestors at the same level.
- Lockstep climbing preserves equal depth and stops exactly at the deepest shared ancestor.
- Ancestor detection happens naturally: if
bdescends froma, aligning depths liftsbup toa, and the loop exits immediately with LCA equal toa. - Same employee case (
a == b) is treated as the ancestor case, returning the employee's manager.
Complexity
Time: O(n) to build the parent array and compute depths, plus O(h) per query where h is tree height. Total O(n) for a single query.
Space: O(n) for the parent and depth arrays.
For multiple queries on the same hierarchy, precompute par and depth once, reducing each query to O(h). Binary lifting can further reduce queries to O(log n) with O(n log n) preprocessing.
Full Solution
from typing import List, Optional
def shared_manager(mode, tree, root, a, b):
# Normalize both representations into a parent array.
# mode == 'children': tree[u] lists direct reports of employee u
# mode == 'parent': tree[u] is the manager of employee u (-1 = no manager)
if mode == 'children':
n = len(tree)
par = [-1] * n
for u in range(n):
for v in tree[u]:
if 0 <= v < n:
par[v] = u
if root is None:
for i in range(n):
if par[i] == -1:
root = i
break
else:
par = list(tree)
n = len(par)
# Validate employee IDs are in range.
if not (0 <= a < n) or not (0 <= b < n):
return None
# Compute depth for all employees iteratively to avoid recursion limits.
depth = [-1] * n
for start in range(n):
if depth[start] != -1:
continue
path = []
curr = start
while curr != -1 and depth[curr] == -1:
path.append(curr)
curr = par[curr]
d = 0 if curr == -1 else depth[curr] + 1
for node in reversed(path):
depth[node] = d
d += 1
def find_root(x):
while par[x] != -1:
x = par[x]
return x
# Employees in different organizational trees have no common manager.
if find_root(a) != find_root(b):
return None
# Standard LCA algorithm: align depths, then climb in parallel.
x, y = a, b
while depth[x] > depth[y]:
x = par[x]
while depth[y] > depth[x]:
y = par[y]
while x != y:
x = par[x]
y = par[y]
# Apply the special rule: if one employee is an ancestor of the other
# (including when a == b), return the ancestor's manager instead.
# If the ancestor is a root, no manager exists.
if x == a or x == b:
manager = par[x]
return manager if manager != -1 else None
return x