# Kth largest element after every insertion

Given an infinite stream of integers, find the k’th largest element at any point of time. It may be assumed that 1 <= k <= n.

```Input:
stream[] = {10, 20, 11, 70, 50, 40, 100, 5, ...}
k = 3
Output:    {_,   _, 10, 11, 20, 40, 50,  50, ...}```

Extra space allowed is O(k).

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

The idea is to use min heap.
1) Store first k elements in min heap.
2) For every element from (k+1)-th to n-th, do following.
……a) Print root of heap.
……b) If current element is more than root of heap, pop root and insert

 `// CPP program to find k-th largest element in a  ` `// stream after every insertion. ` `#include ` `using` `namespace` `std; ` ` `  `int` `kthLargest(``int` `stream[], ``int` `n, ``int` `k) ` `{ ` `   ``// Create a min heap and store first k-1 elements ` `   ``// of stream into  ` `   ``priority_queue<``int``, vector<``int``>, greater<``int``> > pq; ` ` `  `   ``// Push first k elements and print "_" (k-1) times ` `   ``for` `(``int` `i=0; i pq.top()) ` `       ``{ ` `           ``pq.pop(); ` `           ``pq.push(stream[i]); ` `       ``}   ` `   ``}   ` ` `  `   ``// Print last k-th largest element (after ` `   ``// (inserting last element) ` `   ``cout << pq.top(); ` `} ` ` `  `// Driver code ` `int` `main() ` `{ ` `   ``int` `arr[] = {10, 20, 11, 70, 50, 40, 100, 55}; ` `   ``int` `k = 3; ` `   ``int` `n = ``sizeof``(arr)/``sizeof``(arr[0]); ` `   ``kthLargest(arr, n, k); ` `   ``return` `0; ` `} `

Output:
```_ _ 10 11 20 40 50 55
```

If stream contains elements of non-primitive types, we may define our own compactor function and create a priority_queue accordingly.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.