FastPrepKth Smallest Element in a Binary Search Tree

Kth Smallest Element in a Binary Search Tree

Salesforce logoSalesforce● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Insert the values in insertionOrder into an initially empty binary search tree in the given order. Then return the kth-smallest key, where k is one-indexed.

Use an iterative inorder traversal and stop as soon as the kth node is visited.

Function

kthSmallest(insertionOrder: int[], k: int) → int

Examples

Example 1

insertionOrder = [5,3,6,2,4,1]k = 3return = 3

The inorder sequence is [1,2,3,4,5,6], whose third value is 3.

Example 2

insertionOrder = [2,1,3]k = 1return = 1

The first node visited by inorder traversal has key 1.

Constraints

  • 1 <= insertionOrder.length <= 100000.
  • All values in insertionOrder are distinct signed 32-bit integers.
  • 1 <= k <= insertionOrder.length.

More Salesforce problems

See Salesforce hiring insights
public int kthSmallest(int[] insertionOrder, int k) {
    // TODO: build the BST and stop the inorder traversal at rank k.
}
insertionOrder[5,3,6,2,4,1]
k3
expected3
Checking account…