Skip to the code
cf.
+50 XP

#374 Common Manager Queries for an Org Chart

hard

A large company directory shows, for any two people, their closest shared manager. There are n people numbered 0 to n - 1. managers[i] is the direct manager of person i, or -1 for the one person at the top. People are not listed in any particular order.

Write commonManagers(managers, queries) where each query is [a, b]. For each query, return the lowest common ancestor of a and b: the deepest person who is a or above a, and also b or above b. If a manages b (directly or not), the answer is a. Aim for about O(log n) per query.

Example 1

Input: managers = [-1,0,0,1,1,2,2], queries = [[3,4],[3,6],[5,2]]
Output: [1,0,2]

3 and 4 both report to 1. 3 and 6 only meet at 0. 2 manages 5.

Example 2

Input: managers = [-1,0], queries = [[1,1],[0,1]]
Output: [1,0]

A person is their own common manager with themself.

Constraints

  • 1 <= n <= 5 * 10^4
  • 1 <= queries.length <= 5 * 10^4
  • The managers form one tree.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).