Lowest common manager in an org chart
I was asked this
No reports yet. Sign in to say where you were asked it.
A company's reporting structure is a rooted tree. Each person is an Employee with a unique name and a list reports of the people who report to them directly. The root is the CEO, and every other employee has exactly one direct manager.
Implement:
def lowest_common_manager(root: Employee, a: Employee, b: Employee) -> Employee
Return the lowest common manager of a and b: the employee farthest from the CEO whose reporting tree contains both of them. An employee counts as part of their own reporting tree, so if a manages b (directly or through others), the answer is a.
Constraints
- 1 <= number of employees <= 10^5. The tree may be very deep (a long single chain), so be careful with recursion depth.
- Each employee has any number of direct reports.
- Ask your interviewer whether
aandbare guaranteed to be in the tree. If not, returnNonewhen either is missing.
Example 1
Maya
/ | \
Omar Lin Ravi
/ \ |
Ines Theo Kofi
-
lowest_common_manager(Maya, Ines, Theo)returnsOmar. -
lowest_common_manager(Maya, Theo, Kofi)returnsMaya.
Example 2
Using the same tree, lowest_common_manager(Maya, Omar, Ines) returns Omar, because Omar manages Ines and counts as part of his own reporting tree.
Expect follow-ups such as finding the common manager of a whole group of employees, or answering many queries quickly on the same org chart.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.

