The answer depends on your requirements:
how many intervals did you say M?
Of course, the use of M * O (N logN) is redundant, especially when M is large, as well as intervals.
Another approach: using O (N) extra space.
prefix[i] = number of numbers in range 0 to i
Can be done in O (N) time.
Now you need O (1) time for each request:
query[l,r] = prefix[r] - prefix[l - 1] + 1
therefore, the total time complexity of O(N logN + M)
source share