Interview questions · Salesforce
Find the Kth Smallest Value in a Binary Search Tree
Return the one-based kth smallest value from a potentially deep binary search tree represented by parallel value and child-index arrays. Handle empty trees and out-of-range values of k using the specified sentinel.
Problem
Given a binary search tree with distinct integer values, return its kth smallest value, using one-based k.
The tree is represented by parallel arrays: values[i] is node i's value, and left[i] and right[i] are child indices or -1. root is the root index, or -1 for an empty tree.
Function Contract
Implement kthSmallestInBst(values, left, right, root, k) and return the selected integer. Return -1 when the tree is empty or k is outside 1..n.
Constraints & Assumptions
0 <= n = len(values) = len(left) = len(right) <= 200,000.- Child indices are valid or
-1; the arrays form one acyclic tree reachable fromroot. - Values are distinct signed integers and satisfy the binary-search-tree invariant.
kis a signed integer and may be invalid.- A valid tree value may also be
-1; the caller uses the validity ofkto distinguish the error sentinel.
Clarifying Questions to Ask
- Is
kzero-based? No, one-based. - Are duplicate values possible? No.
- May traversal stop as soon as the answer is found? Yes.
- Can the tree be highly unbalanced? Yes; avoid recursion overflow.
Hint: Use the BST's sorted traversal
An iterative in-order traversal visits values in increasing order. Count visits and return at
k.
Examples
values = [3, 1, 4, 2],left = [1, -1, -1, -1],right = [2, 3, -1, -1],root = 0,k = 1returns1.- With the same tree,
k = 3returns3. - An empty tree or
k = 0returns-1.
Evaluation Focus
- Performs in-order traversal and stops after the
kth visit. - Handles invalid
k, empty input, and a depth-ntree without recursion failure. - Runs in
O(h + k)time andO(h)auxiliary space for heighth.
Extensions to Discuss
- How do subtree-size fields support frequent
kth-smallest queries inO(h)time? - Which counters must insertion and deletion update?
- Why do shared-tree counters become difficult when each tenant sees a different filtered subset?
Community answers
Nothing here yet.
Join in on CSWork →