Copies sit together
In a sorted list, all copies of a value sit in one block, like every copy of the same book on a library shelf. So counting them is "where does the block end, minus where does it start".
You already have a search for the start: the first position holding a value at least x.
Start of the block: the first position with a value at least x.
How many 5s?
1
05
15
25
37
49
59
6startend
Search 1: the first value ≥ 5 is at position 1. The 5s start here.
Move 1 of 3
The end is another start
Just past the last x is the first value bigger than x. For whole numbers, that is the first value at least x plus one. So run the same search again with x plus one.
Put the search in its own function and call it twice. The difference of the two answers is the count.
Just past the block: the first position with a value at least x plus one.
x isn't there? Both searches land on the same spot. The count is 0, with no special case.
def first_at_least(x):
low, high = 0, len(nums)
while low < high:
mid = (low + high) // 2
if nums[mid] >= x:
high = mid
else:
low = mid + 1
return low
answers = []
for x in queries:
start = first_at_least(x)
end = first_at_least(x + 1)
answers.append(end - start)
return answers