Kth largest element after every insertion

• Difficulty Level : Medium
• Last Updated : 18 Jun, 2021

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

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

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

 `// 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;``}`

Java

 `// Java Program for the above approach``import` `java.util.*;``class` `GFG``{``  ``static` `void` `kthLargest(``int` `stream[], ``int` `n, ``int` `k)``  ``{` `    ``// Create a min heap and store first k-1 elements``    ``// of stream into``    ``Vector pq = ``new` `Vector(n);` `    ``// Push first k elements and print "_" (k-1) times``    ``for` `(``int` `i = ``0``; i < k - ``1``; i++)``    ``{``      ``pq.add(stream[i]);``      ``System.out.print(``"_ "``);``    ``}``    ``pq.add(stream[k - ``1``]);` `    ``for` `(``int` `i = k; i < n; i++)``    ``{` `      ``// We must insert last element before we``      ``// decide last k-th largest output.``      ``Collections.sort(pq);``      ``System.out.print(pq.get(``0``) + ``" "``);     ``      ``if` `(stream[i] > pq.get(``0``))``      ``{``        ``pq.remove(``0``);``        ``pq.add(stream[i]);``      ``}  ``    ``}  ` `    ``// Print last k-th largest element (after``    ``// (inserting last element)``    ``Collections.sort(pq);``    ``System.out.print(pq.get(``0``));``  ``}` `  ``// Driver code``  ``public` `static` `void` `main(String[] args) {``    ``int` `arr[] = {``10``, ``20``, ``11``, ``70``, ``50``, ``40``, ``100``, ``55``};``    ``int` `k = ``3``;``    ``int` `n = arr.length;``    ``kthLargest(arr, n, k);``  ``}``}` `// This code is contributed by divyeshrabadiya07.`

Python3

 `# Python Program for the above approach``def` `kthLargest(stream, n, k):``    ` `    ``# Create a min heap and store first k-1 elements``    ``# of stream into``    ``pq ``=` `[]``    ` `    ``# Push first k elements and print "_" (k-1) times``    ``for` `i ``in` `range``(k ``-` `1``):``        ``pq.append(stream[i])``        ``print``(``"_ "``, end ``=` `"")``    ``pq.append(stream[k ``-` `1``])   ``    ``for` `i ``in` `range``(k, n):``      ` `        ``# We must insert last element before we``        ``# decide last k-th largest output.``        ``pq.sort()``        ``print``(pq[``0``], end ``=` `" "``)``        ``if``(stream[i] > pq[``0``]):``            ``del` `pq[``0``]``            ``pq.append(stream[i])``    ` `    ``# Print last k-th largest element (after``    ``# (inserting last element)``    ``pq.sort()``    ``print``(pq[``0``], end ``=` `"")` `# Driver code``arr ``=` `[``10``, ``20``, ``11``, ``70``, ``50``, ``40``, ``100``, ``55``]``k ``=` `3``n ``=` `len``(arr)``kthLargest(arr, n, k)` `# This code is contributed by avanitrachhadiya2155`

C#

 `// C# program to find k-th largest element in a ``// stream after every insertion.``using` `System;``using` `System.Collections.Generic;``class` `GFG``{``  ``static` `void` `kthLargest(``int``[] stream, ``int` `n, ``int` `k)``  ``{` `    ``// Create a min heap and store first k-1 elements``    ``// of stream into``    ``List<``int``> pq = ``new` `List<``int``>();` `    ``// Push first k elements and print "_" (k-1) times``    ``for` `(``int` `i = 0; i < k - 1; i++)``    ``{``      ``pq.Add(stream[i]);``      ``Console.Write(``"_ "``);``    ``}``    ``pq.Add(stream[k - 1]);` `    ``for` `(``int` `i = k; i < n; i++)``    ``{` `      ``// We must insert last element before we``      ``// decide last k-th largest output.``      ``pq.Sort();``      ``Console.Write(pq[0] + ``" "``);     ``      ``if` `(stream[i] > pq[0])``      ``{``        ``pq.RemoveAt(0);``        ``pq.Add(stream[i]);``      ``}  ``    ``}  ` `    ``// Print last k-th largest element (after``    ``// (inserting last element)``    ``pq.Sort();``    ``Console.Write(pq[0]);``  ``}` `  ``// Driver code``  ``static` `void` `Main()``  ``{``    ``int``[] arr = {10, 20, 11, 70, 50, 40, 100, 55};``    ``int` `k = 3;``    ``int` `n = arr.Length;``    ``kthLargest(arr, n, k);``  ``}``}` `// This code is contributed by divyesh072019.`

Javascript

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

My Personal Notes arrow_drop_up