15% off all plans & roadmaps Use code
See plansKth Largest Element in a Stream
Updated
TL;DR: Design a class that returns the kth largest score after every new score arrives. Keep a min-heap holding only the k largest scores, so its root is always the answer and each add costs O(log k).
Problem
You run an admissions office and need to track the kth highest test score as applicants submit scores in real time. The cut-off for interviews moves whenever a new score arrives.
Implement a class that, for a fixed integer k, keeps a stream of scores and returns the kth highest score after each new score is added. The kth highest is the kth element when all scores so far are sorted from largest to smallest, so duplicates count separately.
Implement the KthLargest class:
KthLargest(int k, int[] nums)sets up the object with the integerkand the initial scoresnums.int add(int val)adds the scorevalto the stream and returns thekth largest score among all scores so far.
Example 1
Input: ["KthLargest", "add", "add", "add", "add", "add"] [[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]] Output: [null, 4, 5, 5, 8, 8] Explanation: KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]); kthLargest.add(3); // return 4 kthLargest.add(5); // return 5 kthLargest.add(10); // return 5 kthLargest.add(9); // return 8 kthLargest.add(4); // return 8
Example 2
Input: ["KthLargest", "add", "add", "add", "add"] [[4, [7, 7, 7, 7, 8, 3]], [2], [10], [9], [9]] Output: [null, 7, 7, 7, 8] Explanation: KthLargest kthLargest = new KthLargest(4, [7, 7, 7, 7, 8, 3]); kthLargest.add(2); // return 7 kthLargest.add(10); // return 7 kthLargest.add(9); // return 7 kthLargest.add(9); // return 8
Constraints
0 <= nums.length <= 10^41 <= k <= nums.length + 1-10^4 <= nums[i] <= 10^4-10^4 <= val <= 10^4- At most
10^4calls will be made toadd.
Constraints that matter
k <= nums.length + 1means that after the firstaddcall there are always at least k scores, so the kth largest always exists when you answer.- Up to 10^4 calls to
addon a stream that can grow to about 2 * 10^4 scores makes re-sorting on every call a poor fit. It works at this size but costs far more than needed. - The stream only grows and
addis the only query, so you never need scores that fall below the top k. A structure of size k is enough. - Values lie in -10^4..10^4 and duplicates are allowed. Duplicates count as separate scores, so do not deduplicate.
numscan be empty, so the constructor must work with zero initial scores and still answer correctly after the firstadd.
Hints
Hint 1
This is a Top K Elements problem solved with a heap.
Hint 2
Store every score in a list.
Solution
Intuition
This is a Top K Elements problem solved with a heap. The signal is the phrase kth largest on a stream. You are asked for one rank, not a full ordering, and the data keeps arriving.
Picture a waiting room with exactly k reserved seats for the top scorers. The heap is that room, the root is the lowest-scoring seat holder, and that holder is the kth largest.
Notice what the answer depends on. The kth largest score is determined by the k largest scores alone. Everything smaller than the kth largest can never become the answer again, because the answer only moves upward as new scores arrive.
So keep only the k largest scores. Among those k, the answer is the smallest one. That calls for a structure that gives fast access to its minimum and fast insert and removal. A min-heap does exactly that.
Why it stays correct: when a new score arrives, it either beats the current kth largest or it does not. If it does, it enters the top k and the old kth largest drops out. If it does not, nothing changes. In both cases the root of the heap is the new kth largest.
Worked example
Input: commands = ["KthLargest", "add", "add", "add"], params = [[1, []], [5], [3], [10]] Output: [null, 5, 5, 10] Explanation: With k = 1 the answer is the maximum score so far. After adding 5 the maximum is 5. Adding 3 does not change it, so the answer stays 5. Adding 10 makes 10 the new maximum.
Approach 1: Brute force: sort on every add
Store every score in a list. On each add, append the new score, sort the whole list, and read the kth largest by position. This is the version you write before thinking about the stream.
It is correct because a sorted list gives the rank directly. In ascending order the kth largest sits at index len - k.
Steps
- Store
kand a copy ofnumsin a list. - In
add, appendvalto the list. - Sort the list in ascending order.
- Return the element at index
len(list) - k.
Dry run
Example: k = 1, nums = [].
add(5): list becomes [5]. Sorted [5]. Index 1 - 1 = 0, so return 5.add(3): list becomes [5, 3]. Sorted [3, 5]. Index 2 - 1 = 1, so return 5.add(10): list becomes [3, 5, 10]. Sorted [3, 5, 10]. Index 3 - 1 = 2, so return 10.
Output: [null, 5, 5, 10].
Complexity
| Time | O(n log n) per add |
|---|---|
| Space | O(n) |
Here n is the number of scores stored, which can reach about 2 * 10^4. Each add sorts all n scores, and a comparison sort costs O(n log n). The list keeps every score, so memory is O(n). Over m calls the total is O(m * n log n).
PythonTested in our runner
from typing import List, Optional
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.k = k
self.data = list(nums)
def add(self, val: int) -> int:
self.data.append(val)
self.data.sort()
# ascending order: kth largest is k positions from the end
return self.data[len(self.data) - self.k]
JavaTested in our runner
import java.util.*;
class KthLargest {
private final int k;
private final List<Integer> data = new ArrayList<>();
public KthLargest(int k, int[] nums) {
this.k = k;
for (int x : nums) {
data.add(x);
}
}
public int add(int val) {
data.add(val);
Collections.sort(data);
return data.get(data.size() - k);
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class KthLargest {
int k;
vector<int> data;
public:
KthLargest(int k, vector<int>& nums) {
this->k = k;
data = nums;
}
int add(int val) {
data.push_back(val);
sort(data.begin(), data.end());
return data[data.size() - k];
}
};
JavaScriptTested in our runner
var KthLargest = function(k, nums) {
this.k = k;
this.data = [...nums];
};
/**
* @param {number} val
* @return {number}
*/
KthLargest.prototype.add = function(val) {
this.data.push(val);
// default sort is lexicographic, so pass a numeric comparator
this.data.sort((a, b) => a - b);
return this.data[this.data.length - this.k];
};
GoTested in our runner
import "sort"
type KthLargest struct {
k int
data []int
}
func Constructor(k int, nums []int) KthLargest {
d := append([]int{}, nums...)
return KthLargest{k: k, data: d}
}
func (this *KthLargest) add(val int) int {
this.data = append(this.data, val)
sort.Ints(this.data)
return this.data[len(this.data)-this.k]
}
C#Tested in our runner
public class KthLargest {
private int k;
private List<int> data;
public KthLargest(int k, int[] nums) {
this.k = k;
data = new List<int>(nums);
}
public int add(int val) {
data.Add(val);
data.Sort();
return data[data.Count - k];
}
}
Approach 2: Sorted list of the top k
What's slow: the brute force re-sorts the whole list on every call, even though only one new value arrived and the rest was already in order. It also keeps scores that can never matter again.
The insight that fixes it: keep the list sorted at all times and insert each new score at its position found by binary search. Then drop the smallest element whenever the list grows past k. The list holds the k largest scores in order, and the first element is the answer.
Steps
- In the constructor, sort a copy of
numsand keep only its k largest values. - In
add, binary search for the insertion position ofval. - Insert
valat that position. - If the list now holds more than k values, remove the first (smallest) one.
- Return the first element of the list.
Dry run
Example: k = 1, nums = [].
- Constructor: the sorted list is [].
add(5): insert at position 0, list [5]. Size 1 is not above k. Return 5.add(3): insert at position 0, list [3, 5]. Size 2 exceeds 1, so drop 3. List [5]. Return 5.add(10): insert at position 1, list [5, 10]. Size 2 exceeds 1, so drop 5. List [10]. Return 10.
Output: [null, 5, 5, 10].
Complexity
| Time | O(k) per add |
|---|---|
| Space | O(k) |
The list never holds more than k + 1 values. Binary search costs O(log k), but inserting into the middle of an array shifts up to k elements, and removing the first element shifts k more, so each call is O(k). Memory is O(k) because everything below the top k is discarded. The constructor sorts the initial n values in O(n log n).
PythonTested in our runner
from typing import List, Optional
import bisect
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.k = k
# sorted ascending, keep only the k largest
self.data = sorted(nums)[-k:]
def add(self, val: int) -> int:
bisect.insort(self.data, val)
if len(self.data) > self.k:
self.data.pop(0) # drop the smallest
return self.data[0]
JavaTested in our runner
import java.util.*;
class KthLargest {
private final int k;
private final List<Integer> data = new ArrayList<>();
public KthLargest(int k, int[] nums) {
this.k = k;
for (int x : nums) {
data.add(x);
}
Collections.sort(data);
while (data.size() > k) {
data.remove(0);
}
}
public int add(int val) {
int i = Collections.binarySearch(data, val);
if (i < 0) {
i = -i - 1; // insertion point
}
data.add(i, val);
if (data.size() > k) {
data.remove(0);
}
return data.get(0);
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class KthLargest {
int k;
vector<int> data;
public:
KthLargest(int k, vector<int>& nums) {
this->k = k;
data = nums;
sort(data.begin(), data.end());
if ((int)data.size() > k) {
data.erase(data.begin(), data.begin() + (data.size() - k));
}
}
int add(int val) {
data.insert(upper_bound(data.begin(), data.end(), val), val);
if ((int)data.size() > k) {
data.erase(data.begin());
}
return data[0];
}
};
JavaScriptTested in our runner
var KthLargest = function(k, nums) {
this.k = k;
this.data = [...nums].sort((a, b) => a - b);
if (this.data.length > k) {
this.data = this.data.slice(this.data.length - k);
}
};
/**
* @param {number} val
* @return {number}
*/
KthLargest.prototype.add = function(val) {
let lo = 0;
let hi = this.data.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (this.data[mid] < val) {
lo = mid + 1;
} else {
hi = mid;
}
}
this.data.splice(lo, 0, val);
if (this.data.length > this.k) {
this.data.shift();
}
return this.data[0];
};
GoTested in our runner
import "sort"
type KthLargest struct {
k int
data []int
}
func Constructor(k int, nums []int) KthLargest {
d := append([]int{}, nums...)
sort.Ints(d)
if len(d) > k {
d = d[len(d)-k:]
}
return KthLargest{k: k, data: d}
}
func (this *KthLargest) add(val int) int {
i := sort.SearchInts(this.data, val)
this.data = append(this.data, 0)
copy(this.data[i+1:], this.data[i:])
this.data[i] = val
if len(this.data) > this.k {
this.data = this.data[1:]
}
return this.data[0]
}
C#Tested in our runner
public class KthLargest {
private int k;
private List<int> data;
public KthLargest(int k, int[] nums) {
this.k = k;
data = new List<int>(nums);
data.Sort();
if (data.Count > k) {
data.RemoveRange(0, data.Count - k);
}
}
public int add(int val) {
int i = data.BinarySearch(val);
if (i < 0) {
i = ~i; // insertion point
}
data.Insert(i, val);
if (data.Count > k) {
data.RemoveAt(0);
}
return data[0];
}
}

Solution pattern
Top K Elements (Selection/Frequency)
Part of Heap (Priority Queue) Patterns
Approach 3: Min-heap of size kOptimalTop K Elements (Selection/Frequency)
What's slow: the sorted list pays O(k) per call to shift elements, yet you only ever look at its smallest value and remove that value. You never need the full order of the top k.
The insight that fixes it: a min-heap gives the minimum at the root and inserts or removes in O(log k). Keep the k largest scores in a min-heap. Push each new score, and if the heap grows past k, pop the root. The root is then the kth largest.
Steps
- Create an empty min-heap and store
k. - For each value in
nums, run the same logic asadd. - In
add, pushvalonto the heap. - If the heap size is greater than k, pop the smallest value.
- Return the root of the heap without removing it.
Dry run
Example: k = 1, nums = [].
| Step | Action | Heap after push | Size > k? | Heap after pop | Return |
|---|---|---|---|---|---|
| init | empty heap | [] | no | [] | none |
| add(5) | push 5 | [5] | no | [5] | 5 |
| add(3) | push 3 | [3, 5] | yes | [5] (popped 3) | 5 |
| add(10) | push 10 | [5, 10] | yes | [10] (popped 5) | 10 |
Output: [null, 5, 5, 10].
A longer check with k = 3 and nums = [4, 5, 8, 2]: the heap ends the constructor as {4, 5, 8} after 2 is popped. add(3) pushes 3 and pops 3, returning 4. add(5) pushes 5 and pops 4, returning 5. add(10) pops 5 and returns 5. add(9) pops 5 and returns 8.
Complexity
| Time | O(log k) per add |
|---|---|
| Space | O(k) |
The heap never holds more than k + 1 values, so a push and a pop each cost O(log k). Each add does one push, at most one pop and one peek, giving O(log k). The constructor handles n initial values at O(log k) each, so O(n log k). Memory is the heap itself, O(k).
PythonTested in our runner
from typing import List, Optional
import heapq
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.k = k
self.heap: List[int] = []
for x in nums:
self.add(x)
def add(self, val: int) -> int:
heapq.heappush(self.heap, val)
if len(self.heap) > self.k:
heapq.heappop(self.heap) # drop the smallest of the k+1
return self.heap[0] # root is the kth largest
JavaTested in our runner
import java.util.*;
class KthLargest {
private final int k;
private final PriorityQueue<Integer> heap = new PriorityQueue<>();
public KthLargest(int k, int[] nums) {
this.k = k;
for (int x : nums) {
add(x);
}
}
public int add(int val) {
heap.offer(val);
if (heap.size() > k) {
heap.poll();
}
return heap.peek();
}
}
C++Tested in our runner
#include <vector>
#include <queue>
#include <functional>
using namespace std;
class KthLargest {
int k;
priority_queue<int, vector<int>, greater<int>> heap;
public:
KthLargest(int k, vector<int>& nums) {
this->k = k;
for (int x : nums) {
add(x);
}
}
int add(int val) {
heap.push(val);
if ((int)heap.size() > k) {
heap.pop();
}
return heap.top();
}
};
JavaScriptTested in our runner
class MinHeap {
constructor() {
this.a = [];
}
size() {
return this.a.length;
}
peek() {
return this.a[0];
}
push(v) {
const a = this.a;
a.push(v);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (a[p] <= a[i]) break;
[a[p], a[i]] = [a[i], a[p]];
i = p;
}
}
pop() {
const a = this.a;
const top = a[0];
const last = a.pop();
if (a.length > 0) {
a[0] = last;
let i = 0;
const n = a.length;
while (true) {
let s = i;
const l = 2 * i + 1;
const r = 2 * i + 2;
if (l < n && a[l] < a[s]) s = l;
if (r < n && a[r] < a[s]) s = r;
if (s === i) break;
[a[s], a[i]] = [a[i], a[s]];
i = s;
}
}
return top;
}
}
var KthLargest = function(k, nums) {
this.k = k;
this.heap = new MinHeap();
for (const x of nums) {
this.add(x);
}
};
/**
* @param {number} val
* @return {number}
*/
KthLargest.prototype.add = function(val) {
this.heap.push(val);
if (this.heap.size() > this.k) {
this.heap.pop();
}
return this.heap.peek();
};
GoTested in our runner
import "container/heap"
type minHeap []int
func (h minHeap) Len() int { return len(h) }
func (h minHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h minHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *minHeap) Push(x interface{}) { *h = append(*h, x.(int)) }
func (h *minHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[:n-1]
return x
}
type KthLargest struct {
k int
h *minHeap
}
func Constructor(k int, nums []int) KthLargest {
kl := KthLargest{k: k, h: &minHeap{}}
for _, x := range nums {
kl.add(x)
}
return kl
}
func (this *KthLargest) add(val int) int {
heap.Push(this.h, val)
if this.h.Len() > this.k {
heap.Pop(this.h)
}
return (*this.h)[0]
}
C#Tested in our runner
public class KthLargest {
private int k;
private PriorityQueue<int, int> heap = new PriorityQueue<int, int>();
public KthLargest(int k, int[] nums) {
this.k = k;
foreach (int x in nums) {
add(x);
}
}
public int add(int val) {
heap.Enqueue(val, val);
if (heap.Count > k) {
heap.Dequeue();
}
return heap.Peek();
}
}
Common mistakes
- Using a max-heap and trying to read the kth value from it. A max-heap exposes only the largest element, so you must pop k - 1 values to reach the answer. Use a min-heap capped at size k so the root is the answer.
- Never capping the heap, with no
if len(heap) > k: popafter the push. The root then becomes the overall minimum, not the kth largest. Pop whenever the size exceeds k. - Popping before pushing, such as removing the root and then inserting
val. Ifvalis smaller than the root, you throw away a valid top-k score. Push first, then pop the smallest. - Sorting the list inside
addand returningdata[k - 1]after an ascending sort. That index is the kth smallest. Usedata[len - k]for ascending order. - Skipping the initial
numsor inserting them without the size cap. The constructor must apply the same push-and-trim rule to every initial value, or the heap starts oversized and answers wrongly. - Deduplicating scores with a set. The kth largest counts repeats, so for
[7, 7, 7, 7, 8, 3]with k = 4 the answer is 7. Keep duplicates.
Edge cases
k = 1with an emptynums: the firstaddreturns the value itself, since the heap holds one element.k = nums.length + 1: the firstaddbrings the count to exactly k, and the answer is the minimum of all scores so far.- All equal scores, such as
[7, 7, 7, 7]with k = 4: the answer is 7 because each repeat counts as its own score. - A new score smaller than the current kth largest: the answer must not change, and the new score should leave the heap right away.
- Negative scores, such as -10^4: the heap compares signed integers, so the answer is correct with no special handling.
- A very large number of calls, 10^4 adds on 10^4 initial scores: the heap approach stays at O(log k) per call while sorting each time does not.
Follow-ups interviewers ask
- What if the stream is huge and does not fit in memory?
- The heap approach already stores only k values, so memory is O(k) no matter how long the stream runs. You never keep the discarded scores. If k itself is too large for memory, you would need an approximate method or an external structure, but for ordinary k the heap is enough.
- What if k changes between calls?
- A single fixed-size heap no longer works. If k grows, you need scores you already discarded. Keep all scores in an order-statistic structure such as a balanced tree with subtree sizes, and answer each query in O(log n). If k only shrinks, you can keep popping from the same heap.
- How does this relate to Kth Largest Element in an Array?
- It is the static version of the same idea. For one array you can push every element through a min-heap of size k in O(n log k), or use quickselect for O(n) average time. The stream version cannot use quickselect cleanly, because it must answer after every insertion.
Kth Largest Element in a Stream FAQ
What is the time complexity of Kth Largest Element in a Stream?
With a min-heap of size k, each add costs O(log k) and the constructor costs O(n log k) for n initial scores. Space is O(k). Sorting on every call costs O(n log n) per add instead.
Why use a min-heap for Kth Largest Element in a Stream?
You keep the k largest scores, and the kth largest is the smallest of them. A min-heap exposes its smallest value at the root in O(1) and removes it in O(log k). A max-heap would expose the wrong end.
Can Kth Largest Element in a Stream be solved in O(1) extra space?
No, not for general k. The answer after later adds can depend on any of the k largest scores seen so far, so you must remember all k of them. For k = 1 you only need one variable, the running maximum.
How do I solve LeetCode 703 in Python?
Use heapq. Keep a list as the heap, call heappush for each value, and call heappop when the length exceeds k. Return heap[0]. The Python code on this page runs the same logic in the constructor and in add.
How do I solve Kth Largest Element in a Stream in Java?
Use a PriorityQueue<Integer>, which is a min-heap by default. Call offer for each score, call poll when size() exceeds k, and return peek(). No comparator is needed.
Why does the heap hold exactly k elements after the first add?
The constraints guarantee k is at most nums.length + 1. After the first add there are at least k scores in total, so the capped heap is full and its root is a valid kth largest.
Asked at
See which companies ask this — Pro
Related problems
- Last Stone Weight · same technique: Top K Elements (Selection/Frequency)
- Relative Ranks · same technique: Top K Elements (Selection/Frequency)
- Take Gifts From the Richest Pile · same technique: Top K Elements (Selection/Frequency)
- Top K Frequent Elements · same technique: Top K Elements (Selection/Frequency)
- Kth Largest Element in an Array · same technique: Top K Elements (Selection/Frequency)
- Meeting Rooms II · same pattern: Heap (Priority Queue) Patterns
- Design Twitter · same pattern: Heap (Priority Queue) Patterns
- K Closest Points to Origin · same pattern: Heap (Priority Queue) Patterns
- Reorganize String · same pattern: Heap (Priority Queue) Patterns
- Single-Threaded CPU · same pattern: Heap (Priority Queue) Patterns