Arrays January 20 ,2026

Kth Largest Element in a Stream

Problem Statement

You are given an integer k and a stream of integers.

After inserting each element from the stream, you need to report the kth largest element seen so far.

If fewer than k elements have been seen, return -1.

Example

Input
k = 3
stream = [4, 5, 8, 2]

Output
[-1, -1, 4, 4]

Explanation

Stream so farSorted3rd Largest
[4][4]-1
[4,5][5,4]-1
[4,5,8][8,5,4]4
[4,5,8,2][8,5,4,2]4

Why This Problem Is Important

  • Tests heap data structure
  • Classic streaming problem
  • Asked in Amazon, Google, Microsoft
  • Foundation for real-time ranking systems

Approaches Overview

ApproachTechniqueTime (per insert)Space
Brute ForceSort every timeO(n log n)O(n)
BetterMax HeapO(log n)O(n)
OptimalMin Heap of size kO(log k)O(k)

 

Approach 1- Brute Force Approach

Idea

  • Insert element into array
  • Sort array in descending order
  • Pick kth element if exists

Time and Space Complexity

  • Time: O(n log n) per insertion
  • Space: O(n)

 C++ Implementation

#include 
using namespace std;

class KthLargest {
    int k;
    vector arr;
public:
    KthLargest(int k) : k(k) {}

    int add(int val){
        arr.push_back(val);
        sort(arr.begin(), arr.end(), greater());
        if(arr.size() < k) return -1;
        return arr[k-1];
    }
};

int main(){
    KthLargest obj(3);

    cout << obj.add(4) << endl;
    cout << obj.add(5) << endl;
    cout << obj.add(8) << endl;
    cout << obj.add(2) << endl;
    cout << obj.add(10) << endl;
    cout << obj.add(9) << endl;
}

 Java Implementation

import java.util.*;

class KthLargest {
    int k;
    List arr = new ArrayList<>();

    KthLargest(int k){
        this.k = k;
    }

    int add(int val){
        arr.add(val);
        arr.sort(Collections.reverseOrder());
        if(arr.size() < k) return -1;
        return arr.get(k-1);
    }

    public static void main(String[] args){
        KthLargest obj = new KthLargest(3);

        System.out.println(obj.add(4));
        System.out.println(obj.add(5));
        System.out.println(obj.add(8));
        System.out.println(obj.add(2));
        System.out.println(obj.add(10));
        System.out.println(obj.add(9));
    }
}

JavaScript Implementation

class KthLargest {
    constructor(k){
        this.k = k;
        this.arr = [];
    }

    add(val){
        this.arr.push(val);
        this.arr.sort((a,b)=>b-a);
        if(this.arr.length < this.k) return -1;
        return this.arr[this.k-1];
    }
}

let obj = new KthLargest(3);

console.log(obj.add(4));
console.log(obj.add(5));
console.log(obj.add(8));
console.log(obj.add(2));
console.log(obj.add(10));
console.log(obj.add(9));

C# Implementation

using System;
using System.Collections.Generic;

class KthLargest {
    int k;
    List arr = new List();

    public KthLargest(int k){
        this.k = k;
    }

    public int Add(int val){
        arr.Add(val);
        arr.Sort((a,b)=>b.CompareTo(a));
        if(arr.Count < k) return -1;
        return arr[k-1];
    }
}

class Program {
    static void Main(){
        KthLargest obj = new KthLargest(3);

        Console.WriteLine(obj.Add(4));
        Console.WriteLine(obj.Add(5));
        Console.WriteLine(obj.Add(8));
        Console.WriteLine(obj.Add(2));
        Console.WriteLine(obj.Add(10));
        Console.WriteLine(obj.Add(9));
    }
}

 Output

-1
-1
4
4
5
8

Approach 2- Better Approach (Max Heap)

Idea

  • Store all elements in a max heap
  • To get kth largest:
    • Remove top element k times
    • The last removed element is the answer
    • Push removed elements back into heap

This approach is not optimal but helps understand heap mechanics.

Time and Space Complexity

  • Time per insertion: O(k log n)
  • Space: O(n)

Python 

import heapq

class KthLargest:
    def __init__(self, k):
        self.k = k
        self.heap = []

    def add(self, val):
        heapq.heappush(self.heap, -val)

        if len(self.heap) < self.k:
            return -1

        removed = []
        for _ in range(self.k):
            removed.append(heapq.heappop(self.heap))

        ans = -removed[-1]

        for x in removed:
            heapq.heappush(self.heap, x)

        return ans


# Driver Code
obj = KthLargest(3)
print(obj.add(4))
print(obj.add(5))
print(obj.add(8))
print(obj.add(2))
print(obj.add(10))

C++ 

#include 
#include 
#include 
using namespace std;

class KthLargest {
    int k;
    priority_queue pq;  // max heap

public:
    KthLargest(int k) {
        this->k = k;
    }

    int add(int val) {
        pq.push(val);

        if (pq.size() < k)
            return -1;

        vector temp;

        for (int i = 0; i < k; i++) {
            temp.push_back(pq.top());
            pq.pop();
        }

        int ans = temp.back();

        for (int x : temp)
            pq.push(x);

        return ans;
    }
};

int main() {
    KthLargest obj(3);

    cout << obj.add(4) << endl;
    cout << obj.add(5) << endl;
    cout << obj.add(8) << endl;
    cout << obj.add(2) << endl;
    cout << obj.add(10) << endl;

    return 0;
}

Java 

import java.util.*;

class KthLargest {
    int k;
    PriorityQueue pq;

    KthLargest(int k) {
        this.k = k;
        pq = new PriorityQueue<>(Collections.reverseOrder()); // max heap
    }

    int add(int val) {
        pq.add(val);

        if (pq.size() < k)
            return -1;

        List temp = new ArrayList<>();

        for (int i = 0; i < k; i++)
            temp.add(pq.poll());

        int ans = temp.get(k - 1);

        for (int x : temp)
            pq.add(x);

        return ans;
    }
}

public class Main {
    public static void main(String[] args) {
        KthLargest obj = new KthLargest(3);

        System.out.println(obj.add(4));
        System.out.println(obj.add(5));
        System.out.println(obj.add(8));
        System.out.println(obj.add(2));
        System.out.println(obj.add(10));
    }
}

JavaScript 

class MaxHeap {
    constructor() {
        this.data = [];
    }

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

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

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

class KthLargest {
    constructor(k) {
        this.k = k;
        this.heap = new MaxHeap();
    }

    add(val) {
        this.heap.push(val);

        if (this.heap.size() < this.k)
            return -1;

        let temp = [];

        for (let i = 0; i < this.k; i++)
            temp.push(this.heap.pop());

        let ans = temp[this.k - 1];

        for (let x of temp)
            this.heap.push(x);

        return ans;
    }
}

// Driver
let obj = new KthLargest(3);
console.log(obj.add(4));
console.log(obj.add(5));
console.log(obj.add(8));
console.log(obj.add(2));
console.log(obj.add(10));

C# 

using System;
using System.Collections.Generic;

class KthLargest {
    int k;
    PriorityQueue pq;

    public KthLargest(int k) {
        this.k = k;
        pq = new PriorityQueue();
    }

    public int Add(int val) {
        pq.Enqueue(val, -val); // max heap

        if (pq.Count < k)
            return -1;

        List temp = new List();

        for (int i = 0; i < k; i++)
            temp.Add(pq.Dequeue());

        int ans = temp[k - 1];

        foreach (int x in temp)
            pq.Enqueue(x, -x);

        return ans;
    }
}

class Program {
    static void Main() {
        KthLargest obj = new KthLargest(3);

        Console.WriteLine(obj.Add(4));
        Console.WriteLine(obj.Add(5));
        Console.WriteLine(obj.Add(8));
        Console.WriteLine(obj.Add(2));
        Console.WriteLine(obj.Add(10));
    }
}

Output

[-1, -1, 4, 4, 5]

Approach 3 - Optimal Approach (Min Heap of Size k)

Idea

  • Maintain a min heap of size k
  • Heap contains the k largest elements seen so far
  • Top of heap = kth largest element

Time and Space Complexity

  • Time: O(log k) per insertion
  • Space: O(k)

 

Python

import heapq

class KthLargest:
    def __init__(self, k):
        self.k = k
        self.heap = []

    def add(self, val):
        heapq.heappush(self.heap, val)

        if len(self.heap) > self.k:
            heapq.heappop(self.heap)

        if len(self.heap) < self.k:
            return -1

        return self.heap[0]


# Driver Code
kth = KthLargest(3)
print(kth.add(4))   # -1
print(kth.add(5))   # -1
print(kth.add(8))   # 4
print(kth.add(2))   # 4
print(kth.add(10))  # 5

C++

#include 
#include 
using namespace std;

class KthLargest {
    int k;
    priority_queue, greater> pq;

public:
    KthLargest(int k) {
        this->k = k;
    }

    int add(int val) {
        pq.push(val);

        if (pq.size() > k)
            pq.pop();

        if (pq.size() < k)
            return -1;

        return pq.top();
    }
};

int main() {
    KthLargest obj(3);

    cout << obj.add(4) << endl;
    cout << obj.add(5) << endl;
    cout << obj.add(8) << endl;
    cout << obj.add(2) << endl;
    cout << obj.add(10) << endl;

    return 0;
}

Java

import java.util.*;

class KthLargest {
    int k;
    PriorityQueue pq;

    KthLargest(int k) {
        this.k = k;
        pq = new PriorityQueue<>();
    }

    int add(int val) {
        pq.add(val);

        if (pq.size() > k)
            pq.poll();

        if (pq.size() < k)
            return -1;

        return pq.peek();
    }
}

public class Main {
    public static void main(String[] args) {
        KthLargest obj = new KthLargest(3);

        System.out.println(obj.add(4));
        System.out.println(obj.add(5));
        System.out.println(obj.add(8));
        System.out.println(obj.add(2));
        System.out.println(obj.add(10));
    }
}

JavaScript

class MinHeap {
    constructor() {
        this.data = [];
    }

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

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

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

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

class KthLargest {
    constructor(k) {
        this.k = k;
        this.heap = new MinHeap();
    }

    add(val) {
        this.heap.push(val);

        if (this.heap.size() > this.k)
            this.heap.pop();

        if (this.heap.size() < this.k)
            return -1;

        return this.heap.top();
    }
}

// Driver Code
let obj = new KthLargest(3);
console.log(obj.add(4));
console.log(obj.add(5));
console.log(obj.add(8));
console.log(obj.add(2));
console.log(obj.add(10));

C#

using System;
using System.Collections.Generic;

class KthLargest {
    int k;
    PriorityQueue pq;

    public KthLargest(int k) {
        this.k = k;
        pq = new PriorityQueue();
    }

    public int Add(int val) {
        pq.Enqueue(val, val);

        if (pq.Count > k)
            pq.Dequeue();

        if (pq.Count < k)
            return -1;

        return pq.Peek();
    }
}

class Program {
    static void Main() {
        KthLargest obj = new KthLargest(3);

        Console.WriteLine(obj.Add(4));
        Console.WriteLine(obj.Add(5));
        Console.WriteLine(obj.Add(8));
        Console.WriteLine(obj.Add(2));
        Console.WriteLine(obj.Add(10));
    }
}

 Output

-1
-1
4
4
5

Final Summary

ApproachRecommendation
Brute ForceNot interview-friendly
Max HeapConceptual only
Min Heap (size k)Interview standard

 

Next Problem in the Series

Minimum Operations to Make an Array Alternating

Sanjiv
0

You must logged in to post comments.

Related Blogs

Find the S...
Arrays February 02 ,2026

Find the Second Smal...

Array Data...
Arrays December 12 ,2025

Array Data Structure

Array Memo...
Arrays December 12 ,2025

Array Memory Represe...

Array Oper...
Arrays December 12 ,2025

Array Operations and...

Advantages...
Arrays December 12 ,2025

Advantages and Disad...

Arrays in...
Arrays December 12 ,2025

Arrays in C

Vector in...
Arrays December 12 ,2025

Vector in C++ STL

Arrays vs...
Arrays December 12 ,2025

Arrays vs ArrayList...

JavaScript...
Arrays December 12 ,2025

JavaScript Arrays

Binary Sea...
Arrays December 12 ,2025

Binary Search on Arr...

Two Pointe...
Arrays January 01 ,2026

Two Pointers Techniq...

Prefix Sum...
Arrays January 01 ,2026

Prefix Sum Technique

Sliding Wi...
Arrays January 01 ,2026

Sliding Window Techn...

Basics of...
Arrays January 01 ,2026

Basics of Hashing fo...

Traverse a...
Arrays January 01 ,2026

Traverse an Array

Find the S...
Arrays January 01 ,2026

Find the Sum of All...

Find the M...
Arrays January 01 ,2026

Find the Maximum Ele...

Find the M...
Arrays January 01 ,2026

Find the Minimum Ele...

Count Even...
Arrays January 01 ,2026

Count Even and Odd N...

Search an...
Arrays January 01 ,2026

Search an Element in...

Copy One A...
Arrays January 01 ,2026

Copy One Array into...

Reverse an...
Arrays January 01 ,2026

Reverse an Array

Print Alte...
Arrays January 01 ,2026

Print Alternate Elem...

Find the L...
Arrays January 01 ,2026

Find the Length of a...

Check if a...
Arrays January 01 ,2026

Check if an Array is...

Find the F...
Arrays January 01 ,2026

Find the First Eleme...

Find the L...
Arrays January 01 ,2026

Find the Last Elemen...

Count the...
Arrays January 01 ,2026

Count the Number of...

Replace Al...
Arrays January 01 ,2026

Replace All Elements...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at E...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at O...

Find the A...
Arrays January 01 ,2026

Find the Average of...

Print Arra...
Arrays January 01 ,2026

Print Array Elements...

Count the...
Arrays January 01 ,2026

Count the Number of...

Remove Dup...
Arrays January 01 ,2026

Remove Duplicate Ele...

Move All Z...
Arrays January 01 ,2026

Move All Zeros to th...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by K...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by O...

Check if T...
Arrays January 01 ,2026

Check if Two Arrays...

Merge Two...
Arrays January 01 ,2026

Merge Two Sorted Arr...

Find Missi...
Arrays January 01 ,2026

Find Missing Number...

Find Dupli...
Arrays January 01 ,2026

Find Duplicate Eleme...

Count Freq...
Arrays January 01 ,2026

Count Frequency of E...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All U...
Arrays January 01 ,2026

Find All Unique Elem...

Insert an...
Arrays January 01 ,2026

Insert an Element at...

Delete an...
Arrays January 01 ,2026

Delete an Element fr...

Find the I...
Arrays January 01 ,2026

Find the Index of an...

Find Union...
Arrays January 01 ,2026

Find Union of Two Ar...

Find Inter...
Arrays January 01 ,2026

Find Intersection of...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s...

Find the L...
Arrays January 01 ,2026

Find the Largest Sum...

Kadane’s A...
Arrays January 01 ,2026

Kadane’s Algorithm (...

Two Sum Pr...
Arrays January 01 ,2026

Two Sum Problem

Subarray w...
Arrays January 01 ,2026

Subarray with Given...

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Rearrange...
Arrays January 01 ,2026

Rearrange Array Alte...

Leaders in...
Arrays January 01 ,2026

Leaders in an Array

Equilibriu...
Arrays January 01 ,2026

Equilibrium Index of...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s,...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All P...
Arrays January 01 ,2026

Find All Pairs with...

Longest Co...
Arrays January 01 ,2026

Longest Consecutive...

Product of...
Arrays January 01 ,2026

Product of Array Exc...

Maximum Pr...
Arrays January 01 ,2026

Maximum Product Suba...

Find the F...
Arrays January 01 ,2026

Find the First Missi...

Count Inve...
Arrays January 01 ,2026

Count Inversions in...

Rearrange...
Arrays January 01 ,2026

Rearrange Array by S...

Check if A...
Arrays January 01 ,2026

Check if Array Can B...

Trapping R...
Arrays January 01 ,2026

Trapping Rain Water

Maximum Ci...
Arrays January 01 ,2026

Maximum Circular Sub...

Find Minim...
Arrays January 01 ,2026

Find Minimum in Rota...

Search in...
Arrays January 01 ,2026

Search in Rotated So...

Median of...
Arrays January 01 ,2026

Median of Two Sorted...

Merge Inte...
Arrays January 01 ,2026

Merge Intervals

Count Reve...
Arrays January 01 ,2026

Count Reverse Pairs

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Largest Re...
Arrays January 01 ,2026

Largest Rectangle in...

Maximum Su...
Arrays January 01 ,2026

Maximum Sum Rectangl...

Subarray S...
Arrays January 01 ,2026

Subarray Sum Equals...

Count Dist...
Arrays January 01 ,2026

Count Distinct Eleme...

Sliding Wi...
Arrays January 01 ,2026

Sliding Window Maxim...

Find K Max...
Arrays January 01 ,2026

Find K Maximum Eleme...

Minimum Nu...
Arrays January 01 ,2026

Minimum Number of Ju...

Chocolate...
Arrays January 01 ,2026

Chocolate Distributi...

Find All T...
Arrays January 01 ,2026

Find All Triplets Wi...

Kth Smalle...
Arrays January 01 ,2026

Kth Smallest Element...

Maximum Le...
Arrays January 01 ,2026

Maximum Length Biton...

Smallest S...
Arrays January 01 ,2026

Smallest Subarray wi...

Maximum Su...
Arrays January 01 ,2026

Maximum Sum Submatri...

Count Suba...
Arrays January 01 ,2026

Count Subarrays with...

Longest Ar...
Arrays January 01 ,2026

Longest Arithmetic S...

Find the M...
Arrays January 01 ,2026

Find the Median in a...

Split Arra...
Arrays January 01 ,2026

Split Array Largest...

Minimum Co...
Arrays January 01 ,2026

Minimum Cost to Make...

Maximum Pr...
Arrays January 01 ,2026

Maximum Product of T...

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Subarray w...
Arrays January 01 ,2026

Subarray with Maximu...

Find All S...
Arrays January 01 ,2026

Find All Subarrays w...

Partition...
Arrays January 01 ,2026

Partition Array into...

Maximum Ab...
Arrays January 01 ,2026

Maximum Absolute Dif...

Smallest M...
Arrays January 01 ,2026

Smallest Missing Num...

Find Repea...
Arrays January 01 ,2026

Find Repeating and M...

Maximum Le...
Arrays January 01 ,2026

Maximum Length Subar...

Count Suba...
Arrays January 01 ,2026

Count Subarrays with...

Minimum Op...
Arrays January 01 ,2026

Minimum Operations t...

Find Lexic...
Arrays January 01 ,2026

Find Lexicographical...

Find the S...
Arrays February 02 ,2026

Find the Second Larg...

Get In Touch

Kurki bazar Uttar Pradesh

+91-8808946970

techiefreak87@gmail.com