Closest Shared Ancestor for a Group of Org-Chart Nodes
Trees & GraphsModel answerLast updated
Build a validated org-chart tree from manager–report pairs and find the deepest node that is an ancestor of every node in a given set.
Closest Shared Ancestor in an Org Chart
Background
A company's reporting structure forms a rooted tree. Every person has exactly one manager, except the top-level executive who reports to no one. Given a raw list of (report, manager) pairs, your job is to build that tree and answer ancestry queries over it.
What you need to build
1. A constructor that validates and builds the tree
Accept an iterable of (report, manager) pairs where manager is None for the root. Raise a descriptive error for any of these malformed inputs:
- An employee listed under two different managers
- No root exists (implies a cycle)
- More than one root (implies disconnected components)
- Nodes that cannot be reached from the root (a separate cycle floating in the graph)
- An empty input
2. A query method find_common_ancestor(members)
Given a collection of two or more employee identifiers, return the deepest node in the tree that is an ancestor of all of them. "Ancestor" is inclusive: if Alice directly manages Bob, the answer to {Alice, Bob} is Alice. Raise an error if any name is not in the tree, or if fewer than two names are supplied.
Examples
Hierarchy:
Alice
/ \
Bob Carol
/ \ \
Dave Eve Frank
\
Grace
find_common_ancestor(["Dave", "Eve"]) → "Bob"
find_common_ancestor(["Dave", "Frank"]) → "Alice"
find_common_ancestor(["Bob", "Grace"]) → "Bob" # Bob is an ancestor of Grace
find_common_ancestor(["Alice", "Dave"]) → "Alice" # root is in the set
find_common_ancestor(["Dave", "Dave"]) → "Dave" # duplicates are fine
What is expected in your answer
- Define the two APIs above (constructor + query), including what errors they raise and why.
- Describe at least two implementation strategies with their preprocessing and per-query time/space trade-offs.
- Explain why the approach you chose is correct.
- Write clean, working Python. Handle the deep-chain case without hitting Python's default recursion limit.
- Identify at least four edge cases and explain how your code handles each.
- Provide representative unit tests.
Hints
Hint 1
Start by thinking about what makes input invalid before touching the query logic. How do you detect a cycle using only parent pointers and a node count?
Hint 2
For pairwise LCA with binary lifting, you need two things per node: its depth and its 2^j-th ancestor for every j. Once you have those, equalizing depths and jumping in powers of two gives you O(log n) per pair — think about why that binary-search-style descent is guaranteed to stop exactly at the LCA.
Hint 3
When you need the LCA of k nodes, you don't have to call the pairwise function k−1 times. Record DFS entry times during preprocessing: the LCA of the entire set equals the LCA of whichever two nodes have the earliest and latest entry times. Why does that shortcut work?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach and API Design
Clarifying the contract
Before writing any code, nail down a few ambiguities:
- Root representation. The root either appears explicitly as
(CEO, None)or shows up only on the manager side of other pairs. Both should work. - Ancestor-inclusive vs. strict. The most natural definition — and what most interviewers want — is inclusive: a node is its own ancestor. If the interviewer wants the strict nearest manager, return the parent of the result.
- Duplicate names in a query. Allow them; the answer is just that node.
- Error taxonomy. Three distinct error types keep callers able to handle each case differently:
InvalidHierarchyErrorfor bad input structure,UnknownEmployeeErrorfor a query name not in the tree, and plainValueErrorfor a query with fewer than two names.
Validation strategy
Parse (report, manager) pairs into a parent dict. Reject immediately if any employee appears with two different managers. After parsing:
- Zero roots → every node has a parent, so there is a cycle somewhere.
- More than one root → the graph is disconnected.
- Exactly one root → run an iterative DFS. If the DFS visits fewer nodes than exist, the unreachable ones form a floating cycle.
This validation is O(n) and catches every structural defect in one pass.
Two implementation strategies
Naive walk-up (O(n) build, O(k·h) query) Store each node's parent and depth. To find the LCA of two nodes, repeatedly step the deeper node up until both are at the same depth, then step both up together until they meet. Simple to code, but degrades to O(n) per query on a chain-shaped org — bad for a company where everyone reports to the previous hire.
Binary lifting + DFS entry time (O(n log n) build, O(k + log n) query) This is the sweet spot for interviews.
During an iterative DFS, record:
depth[v]— distance from roottin[v]— DFS entry timestamp (an integer counter incremented on first visit)up[0][v] = parent[v], with the root pointing to itself as a sentinel
Then fill the lifting table: up[j][v] = up[j-1][up[j-1][v]]. This gives the 2^j-th ancestor of every node for j up to ⌈log₂ n⌉.
Pairwise LCA with lifting:
- Bring the deeper node up to the same depth as the shallower one using the highest applicable powers of two.
- If they're already equal, that node is the LCA.
- Otherwise, iterate j from high to low: jump both nodes by 2^j whenever their 2^j-th ancestors differ. After the loop, their immediate parent is the LCA.
This is correct because step 3 is a binary search on the distance to the LCA. At each bit, you either take the jump (the LCA is still above) or skip it (you'd overshoot). When done, you're one step below the LCA.
Reducing k nodes to one pairwise call:
Rather than folding k calls as lca(lca(a,b), c)…, use the entry-time trick: the LCA of a set S equals lca2(node with min tin, node with max tin). This costs O(k) to scan for the extremes plus O(log n) for one pairwise call.
Why it works: every node in S sits inside the LCA's DFS subtree, so all their tin values fall in the LCA's interval. If all nodes were inside a single child subtree of the LCA, that child would be a deeper common ancestor — contradicting the LCA being lowest. So the earliest-entry and latest-entry nodes must span at least two different subtrees of the LCA, making their pairwise LCA exactly the LCA of the whole set. The edge case where the LCA itself is in S is handled cleanly: it has the smallest tin in its own subtree, so lca2(LCA, anything_below) returns LCA.
Complexity summary
| Strategy | Build | Query (k nodes) | Space |
|---|---|---|---|
| Parent pointers, walk up | O(n) | O(k · h) | O(n) |
| Binary lifting + tin trick | O(n log n) | O(k + log n) | O(n log n) |
| Euler tour + sparse-table RMQ | O(n log n) | O(k + 1) | O(n log n) |
h is tree height, which is O(n) in the worst case. Binary lifting is the right choice for an interview: the O(1)-query RMQ approach requires more code for little practical gain.
Edge cases
- Root is queried.
tin[root]is 0, so it will be the minimum.lca2(root, x)returns root for any x. - One node is an ancestor of another. Covered by the inclusive definition; the min-tin node will be the ancestor, and the result is correct.
- Deep chain. Use an explicit stack for DFS. A 10 000-node chain would blow Python's default recursion limit of 1 000 with a recursive implementation.
- Self-loop
("CEO", "CEO"). Caught by the "every node has a parent → cycle" check. - Duplicate names in query.
minandmaxbytinreturn the same node;lca2of a node with itself returns that node immediately after depth equalization.
Python implementation
from __future__ import annotations
from typing import Hashable, Iterable, List, Optional, Tuple
class InvalidHierarchyError(ValueError):
pass
class UnknownEmployeeError(KeyError):
pass
class OrgChart:
"""
Builds a validated org-chart tree and answers
'closest shared ancestor' queries in O(k + log n).
"""
def __init__(
self, pairs: Iterable[Tuple[Hashable, Optional[Hashable]]]
) -> None:
parent: dict[Hashable, Optional[Hashable]] = {}
nodes: set[Hashable] = set()
for report, manager in pairs:
if report is None:
raise InvalidHierarchyError("employee identifier cannot be None")
if report in parent and parent[report] != manager:
raise InvalidHierarchyError(
f"{report!r} is listed under two different managers"
)
parent[report] = manager
nodes.add(report)
if manager is not None:
nodes.add(manager)
if not nodes:
raise InvalidHierarchyError("input contains no employees")
# Ensure every node has an entry in parent (managers may only appear
# on the right-hand side and never as a report).
for node in nodes:
parent.setdefault(node, None)
roots = [v for v in nodes if parent[v] is None]
if not roots:
raise InvalidHierarchyError(
"no root found: the hierarchy contains a cycle"
)
if len(roots) > 1:
raise InvalidHierarchyError(
f"hierarchy is disconnected: multiple roots {roots!r}"
)
# --- index nodes -----------------------------------------------
self._names: List[Hashable] = list(nodes)
self._id: dict[Hashable, int] = {name: i for i, name in enumerate(self._names)}
n = len(self._names)
children: List[List[int]] = [[] for _ in range(n)]
for report, manager in parent.items():
if manager is not None:
children[self._id[manager]].append(self._id[report])
# --- iterative DFS: depth, tin, parent array -------------------
root_id = self._id[roots[0]]
depth = [0] * n
tin = [-1] * n
par = [root_id] * n # root is its own sentinel for lifting
timer = 0
stack = [root_id]
while stack:
v = stack.pop()
tin[v] = timer
timer += 1
for c in children[v]:
par[c] = v
depth[c] = depth[v] + 1
stack.append(c)
if timer != n:
raise InvalidHierarchyError(
"cycle detected: some nodes are unreachable from the root"
)
self._depth = depth
self._tin = tin
# --- binary lifting table --------------------------------------
log = max(1, n.bit_length())
up: List[List[int]] = [par]
for j in range(1, log):
prev = up[j - 1]
up.append([prev[prev[v]] for v in range(n)])
self._up = up
self._log = log
# ------------------------------------------------------------------
def _lca2(self, u: int, v: int) -> int:
"""LCA of two node indices using binary lifting."""
# Bring the deeper node up to the same depth
if self._depth[u] < self._depth[v]:
u, v = v, u
diff = self._depth[u] - self._depth[v]
for j in range(self._log):
if (diff >> j) & 1:
u = self._up[j][u]
if u == v:
return u
# Jump both nodes up, stopping just below the LCA
for j in range(self._log - 1, -1, -1):
if self._up[j][u] != self._up[j][v]:
u, v = self._up[j][u], self._up[j][v]
return self._up[0][u]
def find_common_ancestor(self, members: Iterable[Hashable]) -> Hashable:
"""
Return the deepest node that is an ancestor of every member.
Raises:
ValueError – fewer than two members supplied
UnknownEmployeeError – any member is not in the org chart
"""
member_list = list(members)
if len(member_list) < 2:
raise ValueError("at least two employees are required")
ids: List[int] = []
for name in member_list:
if name not in self._id:
raise UnknownEmployeeError(name)
ids.append(self._id[name])
# O(k) scan to find entry-time extremes, then one O(log n) pairwise call
lo = min(ids, key=self._tin.__getitem__)
hi = max(ids, key=self._tin.__getitem__)
return self._names[self._lca2(lo, hi)]
Unit tests
import pytest
def build_chart() -> OrgChart:
return OrgChart([
("Alice", None),
("Bob", "Alice"),
("Carol", "Alice"),
("Dave", "Bob"),
("Eve", "Bob"),
("Frank", "Carol"),
("Grace", "Eve"),
])
def test_siblings():
assert build_chart().find_common_ancestor(["Dave", "Eve"]) == "Bob"
def test_different_subtrees():
assert build_chart().find_common_ancestor(["Dave", "Frank"]) == "Alice"
def test_ancestor_in_query():
assert build_chart().find_common_ancestor(["Bob", "Grace"]) == "Bob"
def test_root_in_query():
assert build_chart().find_common_ancestor(["Alice", "Dave"]) == "Alice"
def test_duplicates():
assert build_chart().find_common_ancestor(["Dave", "Dave"]) == "Dave"
def test_three_nodes():
assert build_chart().find_common_ancestor(["Dave", "Eve", "Frank"]) == "Alice"
def test_unknown_employee():
with pytest.raises(UnknownEmployeeError):
build_chart().find_common_ancestor(["Dave", "Nobody"])
def test_too_few_members():
with pytest.raises(ValueError):
build_chart().find_common_ancestor(["Dave"])
def test_cycle_detection():
with pytest.raises(InvalidHierarchyError):
OrgChart([("A", "B"), ("B", "A")])
def test_disconnected():
with pytest.raises(InvalidHierarchyError):
OrgChart([("A", None), ("B", None), ("C", "B")])
def test_duplicate_manager():
with pytest.raises(InvalidHierarchyError):
OrgChart([("A", None), ("B", "A"), ("B", "C")])
Common mistakes to avoid
- Forgetting the root-as-sentinel. If the root's parent pointer is left uninitialized, the lifting table will contain garbage for the root's ancestors, corrupting depth-equalization for any query that lifts past the root.
- Using recursive DFS on large inputs. A chain of 5 000 nodes silently crashes in CPython. Always use an explicit stack.
- Folding k pairwise LCA calls naively. It works but costs O(k log n) instead of O(k + log n). The entry-time trick is simple to add and worth mentioning.
- Skipping the disconnected-cycle check. The zero-roots and multiple-roots checks catch most bad input, but a cycle that floats entirely below the root (all nodes have parents, yet a subgraph cycles among itself) slips through both. The
timer != nguard after DFS catches it.