A warehouse assigns distinct integer bin labels. Starting from an empty binary search tree, insert the labels 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 arriving packages, you are given its target label t. The package must be stored in the ceiling bin: the smallest existing bin label that is greater than or equal to t. If no such bin exists, report -1 for that query.
Line 1: an integer n.
Line 2: n space-separated distinct integers — the bin labels, 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 ceiling of t_i, or -1 if no bin label is greater than or equal to t_i.
Example 1
Input
5 5 3 8 1 4 3 4 6 9
Expected
4 8 -1
Explanation
Bin labels are {1,3,4,5,8}. Ceiling of 4 is 4 itself; ceiling of 6 is 8; no label is >= 9, so the answer is -1.
Example 2
Input
4 10 20 5 15 2 -100 20
Expected
5 20
Explanation
Bin labels are {5,10,15,20}. Ceiling of -100 is the smallest label, 5; ceiling of 20 is 20 itself.
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 →