← Questions

Largest value shared by two BSTs

0

A coding interview question asked at Google, Amazon and Microsoft. It tests binary search tree, iterator and two pointers.

You are given the roots of two binary search trees, a and b, holding integer values. Return the largest integer that appears in both trees. If the trees share no value, return -1.

Implement:

def largest_common_value(a: TreeNode | None, b: TreeNode | None) -> int: ...

where TreeNode has val, left and right.

Constraints

  • Each tree has between 1 and 10^5 nodes.
  • Every node value is between -10^9 and 10^9.
  • Both inputs are valid BSTs: every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger.
  • Trees may be unbalanced, so the height can be as large as the node count.

Aim for better than O(n) extra memory by using the BST ordering.

Example 1

Tree a values: 1, 3, 6, 8, 10, 12, 15
Tree b values: 2, 4, 6, 7, 10, 11, 14
Output: 10

Both 6 and 10 appear in both trees. 10 is the larger one.

Example 2

Tree a values: 2, 5, 9
Tree b values: 1, 4, 7
Output: -1

No value appears in both trees.

Clarifying questions

  • -1 is a valid node value. If it is the largest shared value, how do we tell it apart from "no match"?
  • Can a tree hold duplicate values? (The strict BST rule says no.)
  • Is O(h) extra memory acceptable, where h is the height, even though h can reach n?
  • Can we modify the trees, for example with Morris traversal?

What a strong answer covers

  • Walks both trees from largest to smallest with two reverse in-order iterators, each on an explicit stack. It advances the iterator holding the larger value and stops at the first equal pair.
  • States the cost: O(h_a + h_b) memory and at most O(n_a + n_b) time. It stops early once the answer is found.
  • Contrasts this with putting one tree into a hash set (O(n) memory).
  • Avoids recursion, since an unbalanced tree can be 10^5 deep.
  • Tests no shared value, a shared maximum, a shared minimum, single-node trees, chain-shaped trees and negative values.

Follow-ups

  • Return every shared value, or the k-th largest shared value.
  • Find the values shared by m trees.
  • O(1) extra memory with Morris traversal, and its cost.
  • The trees change between queries.

Where it's asked

What it tests

binary search tree · iterator · two pointers

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding