FastPrepLowest Common Ancestor in an Inserted BST
Problems/Lowest Common Ancestor in an Inserted BST

Lowest Common Ancestor in an Inserted BST

Amazon logoAmazon● EasyNEW GRADPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: The interview report identifies lowest common ancestor in a binary search tree. The insertion-order runner is a portable practice representation; the judged core task matches the visible source at about 94%.

Build a binary search tree by inserting the distinct values of insertionOrder from left to right. For each insertion, values smaller than the current node go left and larger values go right.

Return the value of the lowest common ancestor of the nodes containing p and q. A node may be an ancestor of itself.

Function

bstLowestCommonAncestor(insertionOrder: int[], p: int, q: int) → int

Examples

Example 1

insertionOrder = [6,2,8,0,4,7,9,3,5]p = 2q = 8return = 6

The two nodes lie on opposite sides of the root, so 6 is their lowest common ancestor.

Example 2

insertionOrder = [6,2,8,0,4,7,9,3,5]p = 2q = 4return = 2

The node containing 2 is an ancestor of the node containing 4.

Example 3

insertionOrder = [5]p = 5q = 5return = 5

A node is its own lowest common ancestor.

Constraints

  • 1 <= insertionOrder.length <= 100000.
  • All values in insertionOrder are distinct integers.
  • p and q both appear in insertionOrder.

More Amazon problems

  • Count Adjacent Symbol Pairs for BPEONSITE INTERVIEW · Seen Nov 2026
  • First Non-Repeating CharacterOA · ONSITE INTERVIEW · Seen Nov 2026
  • Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
See Amazon hiring insights
Saved
class Solution {
    public int bstLowestCommonAncestor(int[] insertionOrder, int p, int q) {
        // Write your solution here.
    }
}
Checking account…