I need to analyze the time complexity of an online algorithm to keep track of minimum $K$ numbers from a stream of $R$ numbers. The algorithm is
- Suppose the $i$th number in the stream is $S_i$.
- Keep a max heap of size $K$.
- If the heap contains fewer than $K$ elements, add $S_i$ to the heap.
- Otherwise: if $S_i$ is smaller than the maximum element in the heap (i.e., the root of the heap), replace the root of the heap with $S_i$ and apply Max-Heapify to the heap; if $S_i$ is greater than or equal to the max element, do nothing.
The problem now is to find the expected number of times the Max Heapify operation will be called, when the stream of integers is of length $R$ and each element of the stream is (iid) uniformly distributed on $[1,N]$.
If the stream were guaranteed to contain only distinct elements, then the answer is easy:
$$E[X] = E[X_1] + E[X_2] + \dots + E[X_R],$$
where $X_i$ is the random indicator variable for occurrence of the Max Heapify operation at the $i$th number in the stream. Now
$$E[X_i] = \Pr[\text{$S_i$ is ranked $\le K$ among first $i$ elements}] = \min(K/i, 1).$$
Hence,
$$E[X] = K + K/(K+1) + \cdots + K/R.$$
That case is relatively easy. But how do we handle the case where the elements are iid uniformly distributed?
[This was actually a Google interview question.]