InterviewPrepKit

Home / Coding / Trees

Lowest Common Ancestor of a Binary Search Tree

medium Original β†—
Solving tips
  • Exploit the BST property: comparing a node's value with p.val and q.val tells you which subtree each target is in, so you never explore both sides.
  • If both targets are less than the node go left, if both greater go right; the first node where they split (or where you land on p or q) is the LCA. O(h) time.
  • This is tail recursion, so convert it to a simple while loop for O(1) space β€” the ideal answer here.
  • Pitfall: don't reach for the generic binary-tree LCA (exploring both children) β€” it's O(n) and signals you missed the BST hint; and note h can be n on a skewed BST.

Problem

Given the root of a binary search tree and two nodes p and q that are guaranteed to exist in it, return their lowest common ancestor (LCA): the deepest node that has both p and q in its subtree. A node counts as its own ancestor, so if p is an ancestor of q, the answer is p itself. All node values are distinct and the BST ordering property holds everywhere.

Examples

  • Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 β†’ Output: 6 2 is in the left subtree of 6 and 8 in the right, so they split at 6.
  • Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 β†’ Output: 2 4 lives inside 2’s subtree, so 2 is its own ancestor and the LCA.
  • Input: root = [2,1], p = 2, q = 1 β†’ Output: 2 The root is an ancestor of everything, including itself.

Constraints

  • 2 <= n <= 10^5 nodes; all values distinct; p != q, both present.
  • Node values fit in a 32-bit signed integer.
  • The BST property is the whole game: expected time is O(h), where h is the height β€” you should never need to explore both subtrees.

Think about it first

Hint 1 Standing at any node, comparing its value with `p.val` and `q.val` tells you which subtree each target lives in β€” without visiting either subtree.
Hint 2 If both targets are smaller than the current node, the LCA is in the left subtree; if both are larger, it's in the right. What's the remaining case?
Hint 3 The first node where `p` and `q` fall on different sides (or where you land exactly on `p` or `q`) is the LCA. That's a single walk down from the root β€” a loop, no recursion needed.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.