K'th largest element in a stream
Last Updated :
11 May, 2025
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 + " ");
}
[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(" "));
[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 + " ");
}
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem