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).

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to find k-th largest element in a 
// stream after every insertion.
#include <bits/stdc++.h>
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<k-1; i++)
   {
      pq.push(stream[i]);
      cout << "_ ";
   }
   pq.push(stream[k-1]);
  
   for (int i=k; i<n; i++)
   {
       // We must insert last element before we
       // decide last k-th largest output.
          cout << pq.top() << " ";
  
       if (stream[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;
}
chevron_right

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.



Improved By : aditya1050

Article Tags :
Practice Tags :