Open In App

K'th largest element in a stream

Last Updated : 11 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an input stream of n integers, represented as an array arr[], and an integer k. After each insertion of an element into the stream, you need to determine the kth largest element so far (considering all elements including duplicates). If k elements have not yet been inserted, return -1 for that insertion. The task is to return an array of size n containing the kth largest element after each insertion step.

Examples: 

Input: arr[] = [1, 2, 3, 4, 5, 6], k = 4
Output: -1 -1 -1 1 2 3
Explanation: The first three insertions have fewer than 4 elements, so output is -1. From the fourth insertion onward, the kth largest elements are 1, 2, and 3 respectively.

Input: arr[] = [10, 20, 5, 15], k = 2
Output: -1 10 10 15
Explanation: First insertion gives -1 as fewer than 2 elements. After second, 2nd largest is 10. Then still 10. After inserting 15, elements are [10, 20, 5, 15]; 2nd largest is now 15.

Input: arr[] = [3, 4], k = 1
Output: 3 4
Explanation: After each insertion, there is at least 1 element, so the 1st largest elements are 3 and then 4.

[Naive Approach] Using Repeated Sorting - O(n*n*log(n)) Time and O(n) Space

The idea is to maintain a sorted array of all elements seen so far to easily access the kth smallest. We sort the array repeatedly after each insertion so that the elements are always in increasing order. This ensures that we can directly pick the kth smallest from a fixed index when we have at least k elements. If fewer than k elements are present, we return -1 since the kth smallest doesn't exist yet.

C++
// C++ program to find the kth smallest element 
// in a stream using Naive Approach
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> kthSmallest(vector<int> arr, int k) {

    // Array to store the final 
    // result after each insertion
    vector<int> res;

    // Array to maintain all 
    // elements seen so far
    vector<int> topK;

    for (int i = 0; i < arr.size(); i++) {

        topK.push_back(arr[i]);

        sort(topK.begin(), topK.end());

        // If at least k elements are present, pick the
        // kth smallest (0-based index: i - k + 1)
        if (topK.size() >= k) {
            res.push_back(topK[i - k + 1]);
        } 
        else {
            
            // Less than k elements so far, push -1
            res.push_back(-1);
        }
    }

    return res;
}

int main() {

    vector<int> arr = {1, 2, 3, 4, 5, 6};
    int k = 4;

    vector<int> res = kthSmallest(arr, k);

    for (int x : res) {
        cout << x << " ";
    }

    return 0;
}
Java
// Java program to find the kth smallest element 
// in a stream using Naive Approach
import java.util.*;

class GfG {

    public static int[] kthSmallest(int[] arr, int k) {

        // Array to store the final 
        // result after each insertion
        int[] res = new int[arr.length];

        // ArrayList to maintain all 
        // elements seen so far
        ArrayList<Integer> topK = new ArrayList<>();

        for (int i = 0; i < arr.length; i++) {

            topK.add(arr[i]);

            Collections.sort(topK);

            // If at least k elements are present, pick the
            // kth smallest (0-based index: i - k + 1)
            if (topK.size() >= k) {
                res[i] = topK.get(i - k + 1);
            } 
            else {

                // Less than k elements so far, push -1
                res[i] = -1;
            }
        }

        return res;
    }

    public static void main(String[] args) {

        int[] arr = {1, 2, 3, 4, 5, 6};
        int k = 4;

        int[] res = kthSmallest(arr, k);

        for (int x : res) {
            System.out.print(x + " ");
        }
    }
}
Python
# Python program to find the kth smallest element 
# in a stream using Naive Approach

def kthSmallest(arr, k):

    # Array to store the final 
    # result after each insertion
    res = []

    # Array to maintain all 
    # elements seen so far
    topK = []

    for i in range(len(arr)):

        topK.append(arr[i])

        topK.sort()

        # If at least k elements are present, pick the
        # kth smallest (0-based index: i - k + 1)
        if len(topK) >= k:
            res.append(topK[i - k + 1])
        else:

            # Less than k elements so far, push -1
            res.append(-1)

    return res

if __name__ == "__main__":

    arr = [1, 2, 3, 4, 5, 6]
    k = 4

    res = kthSmallest(arr, k)

    for x in res:
        print(x, end=" ")
C#
// C# program to find the kth smallest element 
// in a stream using Naive Approach
using System;
using System.Collections.Generic;

class GfG {

    public static int[] kthSmallest(int[] arr, int k) {

        // Array to store the final 
        // result after each insertion
        int[] res = new int[arr.Length];

        // List to maintain all 
        // elements seen so far
        List<int> topK = new List<int>();

        for (int i = 0; i < arr.Length; i++) {

            topK.Add(arr[i]);

            topK.Sort();

            // If at least k elements are present, pick the
            // kth smallest (0-based index: i - k + 1)
            if (topK.Count >= k) {
                res[i] = topK[i - k + 1];
            } 
            else {

                // Less than k elements so far, push -1
                res[i] = -1;
            }
        }

        return res;
    }

    public static void Main() {

        int[] arr = {1, 2, 3, 4, 5, 6};
        int k = 4;

        int[] res = kthSmallest(arr, k);

        foreach (int x in res) {
            Console.Write(x + " ");
        }
    }
}
JavaScript
// JavaScript program to find the kth smallest element 
// in a stream using Naive Approach

function kthSmallest(arr, k) {

    // Array to store the final 
    // result after each insertion
    let res = [];

    // Array to maintain all 
    // elements seen so far
    let topK = [];

    for (let i = 0; i < arr.length; i++) {

        topK.push(arr[i]);

        topK.sort((a, b) => a - b);

        // If at least k elements are present, pick the
        // kth smallest (0-based index: i - k + 1)
        if (topK.length >= k) {
            res.push(topK[i - k + 1]);
        } 
        else {

            // Less than k elements so far, push -1
            res.push(-1);
        }
    }

    return res;
}

// Driver Code
let arr = [1, 2, 3, 4, 5, 6];
let k = 4;

let res = kthSmallest(arr, k);

for (let x of res) {
    process.stdout.write(x + " ");
}

Output
-1 -1 -1 1 2 3 

[Expected Approach] Using Min Heap - O(n*log(k)) Time and O(k) Space

The idea is to efficiently find the kth largest element in a stream using a Min Heap. The thought process is to maintain the k largest elements seen so far in the heap. Since the smallest among these k is the kth largest overall, it is always at the top of the heap. For each new element, if it's larger than the smallest in the heap, we replace the top element to keep only the largest k elements.

Steps to implement the above idea:

  • Initialize an empty Min Heap to maintain the k largest elements from the stream.
  • Traverse each element in the array and check if the heap size is less than k.
  • If heap has less than than k elements, simply insert the current element into the heap.
  • If heap has k elements, compare the current element with the top element of the heap.
  • If current element is greater than the top, replace the top by popping and pushing the new element.
  • After each insertion or replacement, if heap size is at least k, record the top in the result.
  • Else, if less than k elements are present so far, store -1 in the result array.
C++
// C++ program to find the kth largest element 
// in a stream using Min Heap
#include <iostream>
#include <vector>
#include <queue>
using namespace std;

vector<int> kthLargest(vector<int> arr, int k) {

    // Array to store the final results
    vector<int> res;

    // Min Heap to store the k largest elements
    priority_queue<int, vector<int>, greater<int>> minHeap;

    for (int i = 0; i < arr.size(); i++) {

        // If heap has less than k elements,
        // insert directly
        if (minHeap.size() < k) {
            minHeap.push(arr[i]);
        } 

        // If current element is larger 
        // than the smallest in heap,
        // replace the smallest
        else if (arr[i] > minHeap.top()) {
            minHeap.pop();
            minHeap.push(arr[i]);
        }

        // If heap has at least k elements,
        // top of heap is the kth largest so far
        if (minHeap.size() == k) {
            res.push_back(minHeap.top());
        } 

        // Else, not enough elements 
        // to determine kth largest
        else {
            res.push_back(-1);  
        }
    }

    return res;
}

int main() {

    vector<int> arr = {1, 2, 3, 4, 5, 6};
    int k = 4;

    vector<int> res = kthLargest(arr, k);

    for (int x : res) {
        cout << x << " ";
    }

    return 0;
}
Java
// Java program to find the kth largest element 
// in a stream using Min Heap
import java.util.*;

class GfG {

    public static int[] kthLargest(int[] arr, int k) {

        // Array to store the final results
        int[] res = new int[arr.length];

        // Min Heap to store the k largest elements
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();

        for (int i = 0; i < arr.length; i++) {

            // If heap has less than k elements,
            // insert directly
            if (minHeap.size() < k) {
                minHeap.add(arr[i]);
            } 

            // If current element is larger 
            // than the smallest in heap,
            // replace the smallest
            else if (arr[i] > minHeap.peek()) {
                minHeap.poll();
                minHeap.add(arr[i]);
            }

            // If heap has at least k elements,
            // top of heap is the kth largest so far
            if (minHeap.size() == k) {
                res[i] = minHeap.peek();
            } 

            // Else, not enough elements 
            // to determine kth largest
            else {
                res[i] = -1;  
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6};
        int k = 4;

        int[] res = kthLargest(arr, k);

        for (int x : res) {
            System.out.print(x + " ");
        }
    }
}
Python
# Python program to find the kth largest element 
# in a stream using Min Heap
import heapq

def kthLargest(arr, k):

    # Array to store the final results
    res = []

    # Min Heap to store the k largest elements
    minHeap = []

    for i in range(len(arr)):

        # If heap has less than k elements,
        # insert directly
        if len(minHeap) < k:
            heapq.heappush(minHeap, arr[i])

        # If current element is larger 
        # than the smallest in heap,
        # replace the smallest
        elif arr[i] > minHeap[0]:
            heapq.heappop(minHeap)
            heapq.heappush(minHeap, arr[i])

        # If heap has at least k elements,
        # top of heap is the kth largest so far
        if len(minHeap) == k:
            res.append(minHeap[0])

        # Else, not enough elements 
        # to determine kth largest
        else:
            res.append(-1)

    return res

if __name__ == "__main__":

    arr = [1, 2, 3, 4, 5, 6]
    k = 4

    res = kthLargest(arr, k)

    for x in res:
        print(x, end=" ")
C#
// C# program to find the kth largest element 
// in a stream using Min Heap
using System;
using System.Collections.Generic;

class GfG {

    public static int[] kthLargest(int[] arr, int k) {

        // Array to store the final results
        int[] res = new int[arr.Length];

        // List to simulate the Min Heap
        List<int> minHeap = new List<int>();

        for (int i = 0; i < arr.Length; i++) {

            // If heap has less than k elements,
            // insert directly
            if (minHeap.Count < k) {
                minHeap.Add(arr[i]);
                minHeap.Sort(); 
            } 

            // If current element is larger 
            // than the smallest in heap,
            // replace the smallest
            else if (arr[i] > minHeap[0]) {
                minHeap.RemoveAt(0);
                minHeap.Add(arr[i]);
                minHeap.Sort();
            }

            // If heap has at least k elements,
            // top of heap is the kth largest so far
            if (minHeap.Count == k) {
                res[i] = minHeap[0];
            } 

            // Else, not enough elements 
            // to determine kth largest
            else {
                res[i] = -1;  
            }
        }

        return res;
    }

    public static void Main() {
        int[] arr = {1, 2, 3, 4, 5, 6};
        int k = 4;

        int[] res = kthLargest(arr, k);

        foreach (int x in res) {
            Console.Write(x + " ");
        }
    }
}
JavaScript
// JavaScript program to find the kth largest element 
// in a stream using Min Heap
class MinHeap {
    constructor() {
        this.heap = [];
    }

    push(val) {
        this.heap.push(val);
        this.heap.sort((a, b) => a - b);
    }

    pop() {
        return this.heap.shift();
    }

    top() {
        return this.heap[0];
    }

    size() {
        return this.heap.length;
    }
}

function kthLargest(arr, k) {

    // Array to store the final results
    let res = [];

    // Min Heap to store the k largest elements
    let minHeap = new MinHeap();

    for (let i = 0; i < arr.length; i++) {

        // If heap has less than k elements,
        // insert directly
        if (minHeap.size() < k) {
            minHeap.push(arr[i]);
        } 

        // If current element is larger 
        // than the smallest in heap,
        // replace the smallest
        else if (arr[i] > minHeap.top()) {
            minHeap.pop();
            minHeap.push(arr[i]);
        }

        // If heap has at least k elements,
        // top of heap is the kth largest so far
        if (minHeap.size() == k) {
            res.push(minHeap.top());
        } 

        // Else, not enough elements 
        // to determine kth largest
        else {
            res.push(-1);  
        }
    }

    return res;
}

// Driver Code
let arr = [1, 2, 3, 4, 5, 6];
let k = 4;

let res = kthLargest(arr, k);

console.log(res.join(" "));

Output
-1 -1 -1 1 2 3 

[Alternate Approach] Using Tree Set - O(n*log(k)) Time and O(k) Space

The idea is to maintain a set of the k largest elements seen so far similar to the previous approach. As we process each element, we insert it into the set, and if its size exceeds k, we remove the smallest. This ensures the smallest in the set is always the kth largest. We add -1 if fewer than k elements have been seen.

C++
// C++ program to find the kth largest element 
// in a stream using set
#include <iostream>
#include <vector>
#include <set>
using namespace std;

vector<int> kthLargest(vector<int> arr, int k) {

    // Array to store the final results
    vector<int> res;

    set<int> st;

    for (int i = 0; i < arr.size(); i++) {

        // Insert current element in the set (st)
        st.insert(arr[i]);

        // If the size of the set exceeds k,
        // remove the smallest element
        if (st.size() > k) {
            st.erase(st.begin()); 
        }

        // If set size is at least k, top 
        // element will be the kth largest
        if (st.size() == k) {
            
            // The first element is the kth largest
            res.push_back(*st.begin());  
        } 
        else {
            
            // Less than k elements so far, push -1
            res.push_back(-1);
        }
    }

    return res;
}

int main() {

    vector<int> arr = {1, 2, 3, 4, 5, 6};
    int k = 4;

    vector<int> res = kthLargest(arr, k);

    for (int x : res) {
        cout << x << " ";
    }

    return 0;
}
Java
// Java program to find the kth largest element 
// in a stream using set
import java.util.*;

class GfG {

    public static int[] kthLargest(int[] arr, int k) {

        // Array to store the final results
        int[] res = new int[arr.length];

        TreeSet<Integer> st = new TreeSet<>();

        for (int i = 0; i < arr.length; i++) {

            // Insert current element in the set (st)
            st.add(arr[i]);

            // If the size of the set exceeds k,
            // remove the smallest element
            if (st.size() > k) {
                st.pollFirst();
            }

            // If set size is at least k, top 
            // element will be the kth largest
            if (st.size() == k) {
                
                // The first element is the kth largest
                res[i] = st.first();  
            } 
            else {
                
                // Less than k elements so far, push -1
                res[i] = -1;
            }
        }

        return res;
    }

    public static void main(String[] args) {

        int[] arr = {1, 2, 3, 4, 5, 6};
        int k = 4;

        int[] res = kthLargest(arr, k);

        for (int x : res) {
            System.out.print(x + " ");
        }
    }
}
Python
# Python program to find the kth largest element 
# in a stream using set
import bisect

def kthLargest(arr, k):

    # Array to store the final results
    res = []

    st = []

    for i in range(len(arr)):

        # Insert current element in the set (st)
        bisect.insort(st, arr[i])

        # If the size of the set exceeds k,
        # remove the smallest element
        if len(st) > k:
            st.pop(0)

        # If set size is at least k, top 
        # element will be the kth largest
        if len(st) == k:
            
            # The first element is the kth largest
            res.append(st[0])  
        else:
            
            # Less than k elements so far, push -1
            res.append(-1)

    return res

if __name__ == "__main__":

    arr = [1, 2, 3, 4, 5, 6]
    k = 4

    res = kthLargest(arr, k)

    for x in res:
        print(x, end=" ")
C#
// C# program to find the kth largest element 
// in a stream using set
using System;
using System.Collections.Generic;

class GfG {

    public static int[] kthLargest(int[] arr, int k) {

        // Array to store the final results
        int[] res = new int[arr.Length];

        SortedSet<int> st = new SortedSet<int>();

        for (int i = 0; i < arr.Length; i++) {

            // Insert current element in the set (st)
            st.Add(arr[i]);

            // If the size of the set exceeds k,
            // remove the smallest element
            if (st.Count > k) {
                st.Remove(st.Min);
            }

            // If set size is at least k, top 
            // element will be the kth largest
            if (st.Count == k) {
                
                // The first element is the kth largest
                res[i] = st.Min;  
            } 
            else {
                
                // Less than k elements so far, push -1
                res[i] = -1;
            }
        }

        return res;
    }

    static void Main() {

        int[] arr = {1, 2, 3, 4, 5, 6};
        int k = 4;

        int[] res = kthLargest(arr, k);

        foreach (int x in res) {
            Console.Write(x + " ");
        }
    }
}
JavaScript
// JavaScript program to find the kth largest element 
// in a stream using set

function kthLargest(arr, k) {

    // Array to store the final results
    let res = [];

    let st = [];

    for (let i = 0; i < arr.length; i++) {

        // Insert current element in the set (st)
        st.push(arr[i]);
        st.sort((a, b) => a - b);

        // If the size of the set exceeds k,
        // remove the smallest element
        if (st.length > k) {
            st.shift();
        }

        // If set size is at least k, top 
        // element will be the kth largest
        if (st.length == k) {
            
            // The first element is the kth largest
            res.push(st[0]);  
        } 
        else {
            
            // Less than k elements so far, push -1
            res.push(-1);
        }
    }

    return res;
}

// Driver Code
let arr = [1, 2, 3, 4, 5, 6];
let k = 4;

let res = kthLargest(arr, k);

for (let x of res) {
    process.stdout.write(x + " ");
}

Output
-1 -1 -1 1 2 3 

Next Article

Similar Reads