KatInterview

Lowest Shared Ancestor in Organization Hierarchy

Trees & GraphsAuto-graded · 23 test cases
MediumAuto-gradedTrees & Graphstreelowest-common-ancestordepth-first-search

Last 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 where supervisors[i] gives the direct supervisor of person i, or -1 if person i is the organization head
  • people: 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 p starts at p themselves, continues to supervisors[p], then to that person's supervisor, and so forth until reaching the organization head
  • A person x is a shared ancestor if x appears 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 <= 100000 where n = len(supervisors)
  • Exactly one entry in supervisors equals -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 people are 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