Given an infinite stream of integers, return the element representing the k'th largest element in the stream.

In the previous post, we have discussed several methods to find k'th largest element in an array. In this post, we are given an infinite stream instead of a fixed-length array.

 
For example,

Input:  Infinite stream of integers
 
4
5
12
8
9
10
20
42

 
Output:
 
The k’th largest element is NA.
The k’th largest element is NA.
The k’th largest element is 4
The k’th largest element is 5
The k’th largest element is 8
The k’th largest element is 9
The k’th largest element is 10
The k’th largest element is 12

Practice this problem

1. Brute-Force Solution

A simple solution is to maintain an array of size k for storing the top k largest elements among all elements encountered so far in the stream. The array should be sorted in ascending order to find the k'th largest element in constant time. Now, the first element in the sorted array is the k'th largest element.

The idea is to compare each incoming element n in the stream with the current k'th largest element x. If n is more than x, remove x from the sorted array and push n into the array in sorted order. If n is less than x, ignore it.

The time complexity of processing a new element in the stream using this approach is O(k) since we need to sort the array every time. The k'th largest element can be retrieved in O(1) time. The additional space used by the program is O(k).

2. Using Self-balancing BST

Another solution is to use a self-balancing BST. The basic idea for processing a new element remains the same. The k'th largest element will be the smallest element in the BST. The time complexity of processing a new element improves to O(log(k)). However, the time taken for finding the k'th largest element increases to O(log(k)). The additional space used by the program remains O(k).

3. Using Priority Queue

The recommended solution to target this problem is using the priority queue. The idea is to keep track of the top k largest elements using a min-heap of size k. The advantage of using the min-heap is that the k'th largest element is always present at the root and can be retrieved in constant time.

The idea is to compare each incoming element n in the stream with the root element of min-heap r. If n is more than r, replace r with n and call the Heapify procedure on the modified heap’s root. If n is less than r, ignore it.

The time complexity of processing a new element in the stream using this approach is O(log(k)), while the time taken for finding the k'th largest element improves to O(1). The additional space used by the program is O(k).

 
Following is the implementation in C++, Java, and Python based on the min-heap solution:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code