Skip to content
mlmentorship

Lowest Common Ancestor in a BST

Follow both BST targets together until their routes split, state the membership precondition, and add presence evidence when ordering or membership changes.

Published · 14 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Lowest Common Ancestor in a BST

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A finite strict binary search tree and two target references that are actual nodes in that tree. Output. Return their lowest common ancestor as the original node object, not a value or copied node. Rules. Values are unique integers, with no cycles or shared children. A node counts as its own ancestor. The targets may be identical or one may be the other's ancestor. Both targets must exist; missing targets require the checked variant below. Preserve the tree. Example. In a BST with root 6 and children 2 and 8, those children have common ancestor node 6. If node 4 lies below node 2, targets 2 and 4 instead return node 2.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

BST ordering discards one whole side until the targets split at their lowest shared ancestor.

Problem trace

Stop where the targets split, or where one equals the current node

Worked example: stop when the targets split or one equals the current nodeAt node 6 with targets 2 and 8, their search directions split. If one target is 6 itself, that same node is already the ancestor.Stop at a split or at a target thatequals this nodeTargets two and eight: their childdirections split628Stop at six in both cases.Targets six and eight: six alreadyoccupies the root628Stop at six in both cases.
Read it this way: At node 6 with targets 2 and 8, their search directions split. If one target is 6 itself, that same node is already the ancestor. If one target is the current node itself, must both targets lie in different child subtrees?
Full interview answer 14 min read

Find the deepest original tree node that is an ancestor of both given target nodes.

Problem

Input. A finite strict binary search tree and two target references that are actual nodes in that tree.

Output. Return their lowest common ancestor as the original node object, not a value or copied node.

Rules. Values are unique integers, with no cycles or shared children. A node counts as its own ancestor. The targets may be identical or one may be the other’s ancestor. Both targets must exist; missing targets require the checked variant below. Preserve the tree.

Example. In a BST with root 6 and children 2 and 8, those children have common ancestor node 6. If node 4 lies below node 2, targets 2 and 4 instead return node 2.

Picture

Keep targets three and five fixed while the current root changes.

Current rootTarget comparisonsDecision
6Both smallerMove left to 2
2Both largerMove right to 4
43 < 4 < 5Return this node

Problem trace

Stop where the targets split, or where one equals the current node

Input and goalFind the lowest node whose subtree contains both target nodes.
Start at root 6Both targets are smaller: 3 < 6 and 5 < 6. The first branch moves root to 6.left at node 2.
root=6first=3second=5628047935
visited3, 5
Original coordinate inventory
6root=6/\28/\/\0479/\3first=35second=5
inputfirst=3, second=5currentRootroot=6targetsfirst=3, second=5decisionboth smaller -> move left to 2
root
(0, 3)
first
(6, 1)
second
(6, 3)

Recognize it
Both target nodes are in a BST, so comparing both values with the current root reveals whether their lowest common ancestor must be entirely left, entirely right, or current.
Keep true
At the start of every loop iteration, the current root’s subtree contains both targets; moving only when both values are on the same side preserves that fact.
Reuse it
In an ordered search tree, track where multiple target values fall relative to the current separator; the first separator they do not share is their lowest common routing point.
Both targets are smaller: 3 < 6 and 5 < 6. The first branch moves root to 6.left at node 2. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is node 4 lower than the other ancestors containing both targets? What happens if a target equals the current node?
Reference drawing

Problem trace

Stop where the targets split, or where one equals the current node

Worked example: stop when the targets split or one equals the current nodeAt node 6 with targets 2 and 8, their search directions split. If one target is 6 itself, that same node is already the ancestor.Stop at a split or at a target thatequals this nodeTargets two and eight: their childdirections split628Stop at six in both cases.Targets six and eight: six alreadyoccupies the root628Stop at six in both cases.
Execution trace
Input and goalFind the lowest node whose subtree contains both target nodes.
Start at root 6Both targets are smaller: 3 < 6 and 5 < 6. The first branch moves root to 6.left at node 2.
root=6first=3second=5628047935
visited3, 5
Original coordinate inventory
6root=6/\28/\/\0479/\3first=35second=5
inputfirst=3, second=5currentRootroot=6targetsfirst=3, second=5decisionboth smaller -> move left to 2
root
(0, 3)
first
(6, 1)
second
(6, 3)

Recognize it
Both target nodes are in a BST, so comparing both values with the current root reveals whether their lowest common ancestor must be entirely left, entirely right, or current.
Keep true
At the start of every loop iteration, the current root’s subtree contains both targets; moving only when both values are on the same side preserves that fact.
Reuse it
In an ordered search tree, track where multiple target values fall relative to the current separator; the first separator they do not share is their lowest common routing point.
Both targets are smaller: 3 < 6 and 5 < 6. The first branch moves root to 6.left at node 2. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is node 4 lower than the other ancestors containing both targets? What happens if a target equals the current node?
Read it this way: At node 6 with targets 2 and 8, their search directions split. If one target is 6 itself, that same node is already the ancestor. If one target is the current node itself, must both targets lie in different child subtrees?

Code

Use this node type for a local run.

from dataclasses import dataclass


@dataclass
class TreeNode:
   val: int
   left: "TreeNode | None" = None
   right: "TreeNode | None" = None
def lowest_common_ancestor_bst(
   root: TreeNode, first: TreeNode, second: TreeNode
) -> TreeNode:
   while True:
      if first.val < root.val and second.val < root.val:
         root = root.left
      elif first.val > root.val and second.val > root.val:
         root = root.right
      else:
         return root

Preserve Both Targets Together

At each iteration, the current subtree contains both targets. Moving only when both values choose one side preserves that fact.

If the routes split, no single child subtree can contain both targets. The current node is therefore the lowest shared ancestor.

If a target equals the current root, that root is already the answer. For targets four and five, return four.

The returned object is an existing node, not a copied value. Neither target nor any tree link changes.

Time is for tree height ; auxiliary space is . An unbalanced BST can have linear height.

Do Not Infer Membership from a Split

The function compares values but never verifies target membership. An absent target can produce an unsupported split or reach None.

For example, two and absent value 99 split at root six. That does not prove both targets exist.

The platform supplies TreeNode with val, left, and right; this snippet assumes that definition.

Recall: Why not move according to only one target? That move could discard the other and break containment.

Check Possibly Absent Values

Choose this when: Callers supply values without promising membership.

Find both actual nodes first. Return None if either search fails; otherwise reuse the original node-based search.

def lca_present_values(root, first_value, second_value):
   def find(value):
      node = root
      while node and node.val != value:
         node = node.left if value < node.val else node.right
      return node

   first, second = find(first_value), find(second_value)
   if first is None or second is None:
      return None
   return lowest_common_ancestor_bst(root, first, second).val

The interface returns an ancestor value rather than a node object. Values three and five return four; two and 99 return None.

Two membership searches and one ancestor search still take total time and auxiliary space.

Strict unique values remain required. Equal-valued but distinct nodes need a different identity and duplicate-placement contract.

Remove the Ordering Assumption

Choose this when: The input is a general unique-valued binary tree and both values must be present.

Every subtree returns a presence mask and any lowest complete ancestor already found.

Bit one records the first target; bit two records the second. Mask three certifies both, including one node serving both roles.

def general_lca_values(root, first_value, second_value):
   def visit(node):
      if node is None:
         return None, 0
      left_result, left_mask = visit(node.left)
      right_result, right_mask = visit(node.right)
      own = (1 if node.val == first_value else 0) | (2 if node.val == second_value else 0)
      mask = left_mask | right_mask | own
      result = left_result or right_result or (node if mask == 3 else None)
      return result, mask

   result, mask = visit(root)
   return result.val if mask == 3 else None

A lower completed result takes priority over its ancestor. Without one, the current node becomes the answer once its combined mask reaches three.

This visits all nodes in time with recursive stack space. Deep trees can exceed Python’s recursion limit.