InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Lowest Common Ancestor of a Binary Search Tree

medium Original ↗ 00:00

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 is 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 every node, 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 ordering property lets you solve this in O(h) time, where h is the height, without exploring 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug