Skip to content

ORIGINAL CODING QUESTION

Depth of the nearest shared manager

Two people, a and b, sit somewhere in a binary reporting tree. Their nearest shared manager is the deepest node that has both of them in its subtree; a node counts as part of its own subtree, so if a manages b the answer is a itself, and if a equals b it is that node. Return the depth (edges from the root) of that shared node.

Open practice workspace

Original exercise · medium. Editorial role relevance does not imply a company has asked this question.

Input and output

n, then n triples (value,leftChild,rightChild). Node 0 is the root; a missing child is written as -1. Then two node IDs a and b.

Constraints

1 ≤ n ≤ 200; -100 ≤ value ≤ 100; the triples form one connected binary tree and every child ID is larger than its parent ID. 0 ≤ a, b < n.

Example 1

Input

7 10 1 2 -3 3 4 -4 5 6 1 -1 -1 1 -1 -1 1 -1 -1 1 -1 -1 3 4

Output

1

Nodes 3 and 4 both report to node 1, which is at depth 1.

Example 2

Input

7 1 1 2 2 3 -1 3 -1 4 4 5 -1 5 -1 6 6 -1 -1 7 -1 -1 5 6

Output

0

Node 5 is under the left branch and node 6 under the right, so they only meet at the root.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

Walking upward from each person reveals their chain of managers.

Hint 2

Bring the deeper person up to the same depth first.

Hint 3

Then step both upward together until they meet.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →