KatInterview

Closest Shared Ancestor for a Group of Org-Chart Nodes

Trees & GraphsModel answer
MediumModel answerTrees & Graphslowest-common-ancestorbinary-liftingtree-traversal

Last updated

Build a validated org-chart tree from manager–report pairs and find the deepest node that is an ancestor of every node in a given set.

Closest Shared Ancestor in an Org Chart

Background

A company's reporting structure forms a rooted tree. Every person has exactly one manager, except the top-level executive who reports to no one. Given a raw list of (report, manager) pairs, your job is to build that tree and answer ancestry queries over it.

What you need to build

1. A constructor that validates and builds the tree

Accept an iterable of (report, manager) pairs where manager is None for the root. Raise a descriptive error for any of these malformed inputs:

  • An employee listed under two different managers
  • No root exists (implies a cycle)
  • More than one root (implies disconnected components)
  • Nodes that cannot be reached from the root (a separate cycle floating in the graph)
  • An empty input

2. A query method find_common_ancestor(members)

Given a collection of two or more employee identifiers, return the deepest node in the tree that is an ancestor of all of them. "Ancestor" is inclusive: if Alice directly manages Bob, the answer to {Alice, Bob} is Alice. Raise an error if any name is not in the tree, or if fewer than two names are supplied.

Examples

Hierarchy:
         Alice
        /     \
      Bob     Carol
     /   \       \
   Dave  Eve     Frank
              \
              Grace

find_common_ancestor(["Dave", "Eve"])   → "Bob"
find_common_ancestor(["Dave", "Frank"]) → "Alice"
find_common_ancestor(["Bob", "Grace"])  → "Bob"   # Bob is an ancestor of Grace
find_common_ancestor(["Alice", "Dave"]) → "Alice" # root is in the set
find_common_ancestor(["Dave", "Dave"])  → "Dave"  # duplicates are fine

What is expected in your answer

  • Define the two APIs above (constructor + query), including what errors they raise and why.
  • Describe at least two implementation strategies with their preprocessing and per-query time/space trade-offs.
  • Explain why the approach you chose is correct.
  • Write clean, working Python. Handle the deep-chain case without hitting Python's default recursion limit.
  • Identify at least four edge cases and explain how your code handles each.
  • Provide representative unit tests.

Hints

Hint 1

Start by thinking about what makes input invalid before touching the query logic. How do you detect a cycle using only parent pointers and a node count?

Hint 2

For pairwise LCA with binary lifting, you need two things per node: its depth and its 2^j-th ancestor for every j. Once you have those, equalizing depths and jumping in powers of two gives you O(log n) per pair — think about why that binary-search-style descent is guaranteed to stop exactly at the LCA.

Hint 3

When you need the LCA of k nodes, you don't have to call the pairwise function k−1 times. Record DFS entry times during preprocessing: the LCA of the entire set equals the LCA of whichever two nodes have the earliest and latest entry times. Why does that shortcut work?