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.
You are then given q query keys; each query key is guaranteed to already be present in the tree. For each query key x, report its in-order predecessor: the largest key in the tree that is strictly less than x. If x is the minimum key, report -1.
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 x_1 ... x_q, each equal to one of the n keys.
q lines. Line i contains the in-order predecessor of x_i, or -1 if x_i is the minimum key.
Example 1
Input
5 5 3 8 1 4 3 3 1 8
Expected
1 -1 5
Explanation
Keys sorted are 1,3,4,5,8. The predecessor of 3 is 1. The predecessor of 1 (the minimum) is -1. The predecessor of 8 is 5.
Example 2
Input
1 9 1 9
Expected
-1
Explanation
The tree has only one key, 9, so it has no predecessor: -1.
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 →