KatInterview

Shared Manager in Organizational Hierarchy

Trees & GraphsAuto-graded · 28 test cases
MediumAuto-gradedTrees & Graphstreeslowest-common-ancestorgraph-traversal

Last updated

Tests tree traversal, ancestor queries, and handling multiple input formats with a custom precedence rule.

You are building an organizational chart tool that finds the shared manager between two employees.

Write a function that accepts two different representations of an organizational hierarchy and returns the appropriate manager according to specific rules.

Input Formats

Your function receives a mode parameter that determines how the hierarchy is encoded:

Mode "children": The tree parameter is a list where tree[i] contains the list of employee IDs who report directly to employee i. Employee IDs range from 0 to n-1. The root parameter indicates the top of the hierarchy (or None, in which case you should identify the root as the employee with no manager).

Mode "parent": The tree parameter is a list where tree[i] is the ID of the manager of employee i. A value of -1 indicates the employee has no manager (is a root). The root parameter is provided but may be ignored in this mode.

Return Rules

Given two employees a and b:

  • If neither employee is an ancestor of the other in the reporting chain, return their lowest common ancestor (the deepest employee who is an ancestor of both).
  • If one employee reports up through the other (including when a == b), return the parent of that common ancestor instead of the ancestor itself.
  • Return None if no valid manager exists: when employees belong to separate organizational trees, when either employee ID is invalid, or when the rule would require returning the parent of a root node.

Constraints

  • 1 ≤ n ≤ 10,000 where n is the number of employees
  • 0 ≤ a, b < n for valid queries
  • Employee IDs are non-negative integers
  • The hierarchy forms a valid forest (one or more trees with no cycles)
  • Tree height may reach n in degenerate cases

Examples

Example 1

Input: shared_manager('children', [[1, 2], [3, 4], [5], [], [], []], 0, 3, 4)

Output: 1

Example 2

Input: shared_manager('children', [[1, 2], [3, 4], [5], [], [], []], 0, 1, 3)

Output: 0

Example 3

Input: shared_manager('parent', [-1, 0, 0, 1, 1, 2], None, 4, 5)

Output: 0

Example 4

Input: shared_manager('children', [[1, 2], [3, 4], [5], [], [], []], 0, 0, 5)

Output: None

Hints

Hint 1

Convert both input formats to a unified representation before solving the core problem.

Hint 2

The classic depth-alignment algorithm works well: find each node's depth, align to the same level, then climb together until they meet.

Hint 3

Handle the special ancestor case by checking whether the LCA equals one of the input nodes, then returning its parent.