cswork / libraryOpen practice workspace

Interview questions · Adobe

Find the Lowest Common Ancestor Only When Both Nodes Exist

Return the lowest common ancestor of two target values only when both are present in a potentially skewed binary tree. Handle absent targets, equal targets, empty input, and cases where one target is the ancestor.

Problem

Given a binary tree and two target values, return the value of their lowest common ancestor only if both targets occur in the tree. Return null if either target is absent.

Function Contract

Implement lowestCommonAncestorIfPresent(root, p, q).

  • Node values are unique.
  • If p == q, return that value only if it occurs in the tree.
  • An ancestor may be one of the target nodes.

Constraints & Assumptions

  • The tree has at most 100,000 nodes.
  • Node and target values are signed 32-bit integers.
  • The tree may be empty or highly skewed.

Clarifying Questions to Ask

  • Are both targets guaranteed to exist? No; this is the central edge case.
  • Are values unique? Yes, so targets may be identified by value.
  • What if the targets are equal? Presence of that one value is sufficient.
  • Is recursion-depth failure relevant? Yes for a depth-100,000 tree; an iterative solution is acceptable.

Hint: Return evidence with the candidate

A subtree result can carry a candidate ancestor plus flags or a count showing which targets were actually found.

Hint: Do not trust the standard shortcut alone

Returning a found target immediately can produce that target when the other target is missing; validate presence before returning the candidate.

Example

tree = [3,5,1,6,2,0,8,null,null,7,4]
p = 5
q = 4
output = 5

For the same tree with q = 42, return null.

Evaluation Focus

  • Distinguishes a valid ancestor from a partial match.
  • Handles equal targets, an ancestor target, missing nodes, and an empty tree.
  • Visits each node at most a constant number of times.
  • Explains recursive stack risk and an iterative alternative.

Extensions to Discuss

  1. How would parent pointers reduce the problem to intersecting ancestor chains?
  2. How would you answer many LCA queries on one static tree?
  3. What changes when values are not unique and targets are node identities?

Community answers

Nothing here yet.

Join in on CSWork →