Kth Smallest and Largest element in BST

Binary Search Trees Medium Medium
  • This kind of problem is often encountered in databases and data analytics frameworks where sorting and querying operations are commonly performed
  • For example, finding the 'kth' smallest or largest value in a data set is a very common requirement in reporting, where you may want to find things like the top three sales results or the lowest five temperatures recorded
  • Binary Search Trees (BST) are frequently used in these contexts due to their efficient search, insert and delete operations
  • Moreover, Databases can store index keys in a BST format to optimize search time

Given the root node of a binary search tree (BST) and an integer k.

Return the kth smallest and largest value (1-indexed) of all values of the nodes in the tree.

Examples:

Input : root = [3,1,4,null,2] , k = 1

Output : [1, 4]

Explanation : The 1st smallest value in given BST is 1.

The 1st largest value in given BST is 4.

Input : root = [5, 3, 6, 2, null, null, null, 1] , k = 3

Output : [3, 3]

Explanation : The 3rd smallest value in given BST is 3.

The 3rd largest value in given BST is 3.

Input : root = [3,1,4,null,2] , k = 2

Constraints

  • The number of nodes in the tree is n.
  • 1 <= k <= n <= 104
  • 0 <= Node.val <= 105

Hints

  • Perform an inorder traversal while maintaining a counter. Stop when the k-th smallest element is found. Similarly, for k-th largest, perform a reverse inorder traversal.
  • Perform a full inorder traversal and store values in an array. The k-th smallest is at index k-1, and the k-th largest is at index n-k.

Company Tags

GE Healthcare Zomato Cloudflare Medtronic Swiggy Shopify Robinhood IBM Johnson & Johnson Alibaba Cerner Flipkart Bungie Lyft Electronic Arts PayPal Visa Red Hat Roche Boston Consulting Group Mastercard Activision Blizzard Reddit JPMorgan Chase American Express Google Microsoft Amazon Meta Apple Netflix Adobe