Describe an algorithm that, given \(n\) integers in the range 0 to \(k\), preprocesses its input and then answers any query about how many of the \(n\) integers fall into a range \([a \mathinner{.\,.} b]\) in \(O(1)\) time. Your algorithm should use \(\Theta(n + k)\) preprocessing time.
The key insight is to use the counting array from counting sort, but keep it in its cumulative form.
Think of a simpler problem first: how many numbers are \(\leq b\)? If we have a cumulative count array, this is just one lookup. Similarly, how many are \(\leq a - 1\)? Another lookup. The difference gives us the count in range \([a \mathinner{.\,.} b]\).