All practice tasks

Coding (Algo)

Find the Shared Ancestor

Lowest common ancestor · Medium

A hierarchy debugger compares two distinct node values in a serialized binary tree. It needs the deepest reachable node that contains both in its descendant subtree. A node is also considered its own ancestor.

Return the value of the lowest common ancestor of p and q, or null when either value is not reachable from the root.

Input

Call

  • Implement solve(input) and return the result. The provided adapter handles JSON input and output.

Input shape

A JSON object { "tree": (number|null)[], "p": number, "q": number }.

Fields

  • tree is a heap-indexed array: children of index i are 2i+1 and 2i+2. Null or an out-of-range index has no node. Entries below a missing ancestor are unreachable and ignored.
  • p and q are integer node values, not array indexes. All non-null values in tree are unique. p may equal q.

Output

Return value

  • Return a node value or null.
  • If p=q and that node is reachable, return p.
  • A value stored below a null ancestor is absent from the actual tree and cannot satisfy the lookup.

Constraints

  • 0 <= tree.length <= 100000. Node values are integers in [-1000000000,1000000000].
  • This is not a compact breadth-first serialization: missing child slots keep their indexes.

Examples

Example 1

{
  "p": 2,
  "q": 7,
  "tree": [
    10,
    5,
    15,
    2,
    7
  ]
}

Returns

5

5 is the deepest shared ancestor.

Example 2

{
  "p": 5,
  "q": 99,
  "tree": [
    10,
    5,
    15
  ]
}

Returns

null

99 is absent.

Required complexity

O(n) time and O(n) space or better

What this task practices

Find the Shared Ancestor is a coding (algo) interview exercise that trains prompt interpretation, explicit assumptions, a concrete response, and a clear explanation of tradeoffs. The catalog marks it as medium difficulty. It focuses on Technical Reasoning, Testing, Validation. The signed-in workspace provides the tools for the round and evaluates the attempt against task-specific criteria. Reference solutions, hidden checks, evaluator instructions, and candidate work remain private.

Sign in to startThe workspace and evaluation open after sign in.