Lowest Shared Ancestor in Organization Hierarchy
Trees & GraphsAuto-graded · 23 test casesLast updated
Finding the deepest node that lies on the upward path to the root for all given employees in a tree structure.
You're given an organization hierarchy represented as a tree where each person reports to at most one supervisor. People are identified by integers from 0 to n - 1. One person has no supervisor and serves as the organization's head; all others report upward through their supervisors eventually reaching this head.
Write a function that identifies the lowest shared ancestor for a given set of people. The lowest shared ancestor is the person furthest from the organization head who lies on the reporting path from each given person up to the head.
Input
supervisors: A list wheresupervisors[i]gives the direct supervisor of personi, or-1if personiis the organization headpeople: A list of distinct person identifiers for whom you need to find the lowest shared ancestor
Output
Return the identifier of the lowest shared ancestor.
Rules
- The reporting path for person
pstarts atpthemselves, continues tosupervisors[p], then to that person's supervisor, and so forth until reaching the organization head - A person
xis a shared ancestor ifxappears on the reporting path of every person in the input list - Since each person's path includes themselves, if one input person is an ancestor of all others, that person is the answer
- The organization head appears on every reporting path, guaranteeing at least one shared ancestor exists
- All shared ancestors lie along a single path to the head, so exactly one is furthest from the head
Constraints
2 <= n <= 100000wheren = len(supervisors)- Exactly one entry in
supervisorsequals-1; all others are valid person identifiers in[0, n - 1] - Following supervisors upward from any person reaches the head without cycles
2 <= len(people) <= n- All values in
peopleare distinct and within[0, n - 1] - The hierarchy depth can reach
n - 1(a single chain)
Examples
Example 1
Input: lowest_shared_ancestor([-1, 0, 0, 1, 1, 2, 3], [6, 4])
Output: 1
Example 2
Input: lowest_shared_ancestor([-1, 0, 0, 1, 1, 2, 3], [6, 4, 5])
Output: 0
Example 3
Input: lowest_shared_ancestor([-1, 0, 0, 1, 1, 2, 3], [3, 6])
Output: 3
Hints
Hint 1
Consider flipping the perspective: instead of walking up from each person, think about which subtree contains all the target people
Hint 2
A person x appears on employee e's path upward if and only if e is in the subtree rooted at x
Hint 3
Count how many target people fall within each person's subtree, then find the deepest person whose subtree contains all of them
Hint 4
Process nodes in an order where all descendants are handled before their ancestors - reverse level-order traversal works perfectly
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is to reframe the problem: instead of tracing paths upward from each person, we can count how many target people appear in each node's subtree. A person x lies on employee e's upward path precisely when e belongs to the subtree rooted at x. Therefore, x is a shared ancestor when its subtree contains all target people.
The algorithm works in four steps:
-
Build the tree structure: Convert the parent pointers into a children adjacency list and identify the organization head (the person with no supervisor)
-
Generate level-order traversal: Perform breadth-first traversal starting from the head, producing a list where nodes appear in non-decreasing depth order
-
Count subtree targets: Initialize a count for each person (1 if they're in the target list, 0 otherwise). Process nodes in reverse level-order so that every node's descendants are processed before it. As we process each node, add its count to its supervisor's count
-
Find the answer: The first node encountered (in reverse order) whose count equals the target list size is the lowest shared ancestor
Why reverse level-order? Processing in this order guarantees two properties:
- Every child completes before its parent, so counts are finalized when propagated upward
- Deeper nodes are examined first, so the first node with a complete count is the deepest one
Why this works for edge cases: Since each target person starts with a count of 1, if one target person manages all others, that person's subtree count will equal the total number of targets, making them the correct answer.
Complexity
Time: O(n) where n is the number of people. We build the children lists in one pass, perform BFS in O(n), and process the reverse order in O(n). The algorithm's runtime is independent of the target list size beyond the initial O(k) marking step.
Space: O(n) for the children lists, traversal order, and count array.
This approach significantly outperforms the naive solution of walking each person's path and finding the intersection, which would cost O(k · depth) and degrade to around 10^10 operations on chain-shaped hierarchies with large k.
Implementation
from typing import List
def lowest_shared_ancestor(supervisors: List[int], people: List[int]) -> int:
n = len(supervisors)
children = [[] for _ in range(n)]
head = -1
for i, sup in enumerate(supervisors):
if sup == -1:
head = i
else:
children[sup].append(i)
order = [head]
for x in order:
order.extend(children[x])
count = [0] * n
for p in people:
count[p] = 1
target = len(people)
for x in reversed(order):
if count[x] == target:
return x
sup = supervisors[x]
if sup != -1:
count[sup] += count[x]
return head