A sensor logs n distinct integer readings. Starting from an empty binary search tree, insert the readings 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 given q window queries. Query i gives two integers lo_i and hi_i (lo_i ≤ hi_i); report how many readings x in the tree satisfy lo_i ≤ x ≤ hi_i.
Because q queries must each be answered, an efficient solution augments each tree node with the size of its subtree so a count can be derived from the tree's shape without inspecting every node on every query.
Line 1: an integer n.
Line 2: n space-separated distinct integers — the readings, in insertion order.
Line 3: an integer q.
Next q lines: two space-separated integers lo_i hi_i.
q lines. Line i contains the count of readings within [lo_i, hi_i].
Example 1
Input
5 5 3 8 1 4 2 2 5 6 10
Expected
3 1
Explanation
Readings are {1,3,4,5,8}. Window [2,5] contains 3,4,5 (count 3). Window [6,10] contains only 8 (count 1).
Example 2
Input
6 10 20 5 15 1 30 3 0 100 16 25 31 40
Expected
6 1 0
Explanation
Readings are {1,5,10,15,20,30}. Window [0,100] contains all 6. Window [16,25] contains only 20 (count 1). Window [31,40] contains none (count 0).
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 →