At most
Level B. Teaches binary search on a sorted array with first_gt.
You are given n integers (1 ≤ n ≤ 2·10⁵, each from 1 to 10⁹) and q queries (1 ≤ q ≤ 2·10⁵). For each query x, print how many of the integers are at most x.
Input: n, the integers, q, then q lines with x. Output: one line per query.
| Input | Output |
|---|---|
55 1 4 1 931410 | 235 |
3 tests · Ctrl+Enter
Hints
- In the sorted array, the values at most x are a prefix. Its length is the index of the first value greater than x.
b.first_gt(x)is that index, found by binary search in O(log n). It returns?Int,Nonewhen every value is at most x, so?? nis that case.- The four searches,
first_ge,first_gt,last_le,last_lt, are named for what they return, so there is noupper_boundminus one to work out. - Sorting and searching covers the four sorted lookups; a hand-written
while lo < hisearch is what the hand_rolled_answer_search lint flags.