A binary search tree (BST) is built from an empty tree by inserting the given keys one at a time, in the order they appear. Insertion follows the usual rule: starting at the root, go left when the new key is smaller than the current node and right when it is larger, placing the key at the first empty spot. All keys are distinct, so no duplicate insertions occur.\n\nAfter all insertions, report the k-th smallest key stored in the tree, counting from 1 (so k = 1 is the minimum key and k = n is the maximum).\n\n## Input format\n\nLine 1: two integers n and k.\nLine 2: n distinct space-separated integers giving the insertion order.\n\n## Output format\n\nA single integer: the k-th smallest key in the BST.\n\n## Constraints\n\n- 1 <= n <= 100000\n- 1 <= k <= n\n- -1000000000 <= each key <= 1000000000, and all keys are distinct.
Example 1
Input
5 2 8 3 10 1 6
Expected
3
Explanation
Inserting 8, 3, 10, 1, 6 gives keys {1, 3, 6, 8, 10}. In ascending order they are 1, 3, 6, 8, 10, so the 2nd smallest is 3.
Example 2
Input
3 3 5 2 9
Expected
9
Explanation
The keys are {2, 5, 9}; the 3rd smallest (the maximum) is 9.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →