You are given n distinct integers. Starting from an empty binary search tree, insert them in the order given, using the standard BST rule: to insert a key x, walk down from the root, going left if x is smaller than the current node and right if x is larger, until an empty spot is reached, where a new node is created. No rebalancing is performed.
For each of q target values t, find the key in the tree whose absolute difference from t is smallest. If two keys are equally close, report the smaller of the two.
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 t_1 ... t_q — the query targets.
q lines. Line i contains the key closest to t_i (smaller key wins ties).
Example 1
Input
5 5 3 8 1 4 2 6 2
Expected
5 1
Explanation
Keys are {1,3,4,5,8}. For target 6, key 5 is closest (distance 1). For target 2, keys 1 and 3 are equally close (distance 1 each); we output the smaller, 1.
Example 2
Input
3 10 20 15 1 17
Expected
15
Explanation
Keys are {10,15,20}. Distances from 17 are 7, 2, and 3, so 15 is closest.
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 →