Ad platform~15 min2s · 256 MBtarget O(q log n) time, O(1) spacebinary-search
An ad platform logs the bid amounts for one ad slot after an auction, sorted from the smallest to the largest. Several advertisers can bid the same amount.
Analysts ask many questions of one kind: how many bids were at least a low amount and at most a high amount? Both ends of the band count.
Write count_in_bands(bids, bands).
bids is the sorted list of bid amounts, with repeats allowed.bands[j] = [low, high] asks for the number of bids b with low <= b <= high.Input: bids = [2, 4, 4, 7, 9, 9, 15], bands = [[4, 9], [5, 8], [0, 1], [10, 20], [4, 4]]
Output: [5, 1, 0, 1, 2]Take the band [4, 9]. The band starts at the first bid that is not below 4. It ends before the first bid that is above 9. The count is the distance between the two places.
| Search | lo | hi | mid | bids[mid] | Decision |
|---|---|---|---|---|---|
| not below 4 | 0 | 7 | 3 | 7 | not below 4, so hi = 3 |
| not below 4 | 0 | 3 | 1 | 4 | not below 4, so hi = 1 |
| not below 4 | 0 | 1 | 0 | 2 | 2 < 4, so lo = 1 (begin = 1) |
| above 9 | 0 | 7 | 3 | 7 | 7 is not above 9, so lo = 4 |
| above 9 | 4 | 7 | 5 | 9 | 9 is not above 9, so lo = 6 |
| above 9 | 6 | 7 | 6 | 15 | 15 is above 9, so hi = 6 (end = 6) |
The band holds the positions 1 to 5, which is 6 - 1 = 5 bids.
The band [5, 8] holds only the bid 7. The band [0, 1] holds none. The band [10, 20] holds the bid 15. The band [4, 4] holds the two bids of 4.
Input: bids = [], bands = [[0, 5]]
Output: [0]With no bids, every band holds zero.
Input: bids = [3, 3, 3], bands = [[3, 3], [0, 2], [4, 9]]
Output: [3, 0, 0]A band that is exactly the repeated value holds all three bids. A band below and a band above hold none.
0 ≤ bids.length ≤ 100,000, and bids is sorted from smallest to largest, repeats allowed0 ≤ bands.length ≤ 100,000, and each band is [low, high] with low ≤ high0 ≤ bids[i], low, high ≤ 1,000,000,000Counting the bids inside each band by looking at every bid costs about n × q steps, which is 10^10 when both are 100,000. A sorted list lets you find where a band starts and where it ends with two binary searches, and the count is the gap between the two places.