You are given n distinct integers. Starting from an empty binary search tree (BST), insert them in the order given, using the standard BST rule: to insert a key x, walk down from the root comparing x to the current node's key, going left if x is smaller and right if x is larger, until you reach an empty spot, where a new node is created. No rebalancing is ever performed.
You must then answer q independent rank queries. Query i gives an integer k_i (1-indexed); you must report the k_i-th smallest key currently stored in the tree (so k_i = 1 is the minimum key, k_i = n is the maximum key).
Line 1: an integer n.
Line 2: n space-separated distinct integers — the keys, in insertion order.
Line 3: an integer q.
Line 4: q space-separated integers k_1 ... k_q.
q lines. Line i contains the k_i-th smallest key.
Example 1
Input
5 5 3 8 1 4 2 1 5
Expected
1 8
Explanation
Inserting 5,3,8,1,4 gives the key set {1,3,4,5,8}. The 1st smallest is 1 and the 5th smallest is 8.
Example 2
Input
3 10 -2 7 3 2 2 1
Expected
7 7 -2
Explanation
The keys sorted ascending are -2,7,10. The 2nd smallest is 7 (asked twice) and the 1st smallest is -2.
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 →