All practice tasks

Coding (Algo)

Find the Shared Tree Ancestor

Tree traversal · Medium

A tree inspector lets an operator select two entries that can share the same displayed value. To highlight their smallest shared branch, it needs a stable node identity rather than a value search. The saved tree may contain stale entries beneath removed parents.

Return the heap index of the lowest common ancestor of p and q or null if either selected index is absent or unreachable.

Input

Call

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

Input shape

{ tree: (integer | null)[], p: integer | null, q: integer | null }

Fields

  • tree is a binary tree encoded with heap indexes: root 0; children of i are 2i+1 and 2i+2. This is not compact queue serialization.
  • p and q are heap indexes identifying nodes, not values. Each may be null or an integer from 0 through 100000; absent or unreachable indexes are allowed. Values may repeat.

Output

Return value

  • Return an integer heap index or null, never the ancestor value. A node is an ancestor of itself.
  • Reject null indexes, missing slots and nodes behind a null ancestor. Equal values do not make two different indexes the same node.

Constraints

  • 0 <= tree.length <= 100000; each non-null value is an integer from -1000000000 to 1000000000.
  • Do not mutate either input array. Sums fit safe JSON integers. Heap indexing bounds the tree height by 17 at this input limit.

Examples

Example 1

{
  "p": 3,
  "q": 2,
  "tree": [
    8,
    8,
    8,
    1
  ]
}

Returns

0

Example 2

{
  "p": 1,
  "q": 1,
  "tree": [
    8,
    2,
    3
  ]
}

Returns

1

Required complexity

O(h) time and O(1) auxiliary space with heap-index parent arithmetic

What this task practices

Find the Shared Tree 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.