Kth Largest Element in a Stream solution explained

To report the kth largest number in a stream after every new value, keep a min-heap holding only the k largest values seen so far. Its smallest element, the top of the heap, is the kth largest overall. Each new value either is ignored (if it is not bigger than the top) or replaces the top, so every update costs O(log k) time and the structure uses O(k) space.

By Published 7 min read

The problem, in plain terms

Design a class. Its constructor receives a number k and an initial list of integers, which may be shorter than k or even empty. It has one method, add, which takes a new integer, includes it with everything seen before, and returns the kth largest value among all of them, counting duplicates separately. In most versions you are promised that at least k numbers exist whenever add is called, but it is worth asking.

k = 3, start with [12, 4, 30]
add(7)  -> 7     three largest so far: 30, 12, 7
add(25) -> 12    30, 25, 12
add(2)  -> 12    2 is too small to matter
add(40) -> 25    40, 30, 25
add(18) -> 25    18 does not beat 25

k = 3, start with [5]
add(9)  -> none yet (only two numbers seen)
add(1)  -> 1
add(20) -> 5
Two short streams, made up for this page

How the problem is used in interviews

It is a quick test of whether you reach for a heap when a problem says "kth largest" and the data keeps changing. Interviewers like it as a warm-up or as the first half of a harder question (a running median uses two heaps). They listen for the counterintuitive choice of a min-heap to track the largest values, and for how you handle a starting list smaller than k.

A slower starting idea

Keep every number in a sorted list. Each add inserts the new value in its place (binary search finds the spot in O(log n), but shifting elements to make room is O(n)) and then reads the element k positions from the end. Re-sorting the whole list on every add is worse, O(n log n) per call. Either way the cost grows with the length of the stream, and the list keeps values that can never be the answer again.

import bisect

class KthLargestSorted:
    def __init__(self, k, nums):
        self.k, self.seen = k, sorted(nums)

    def add(self, val):
        bisect.insort(self.seen, val)          # O(n) shift per insert
        return self.seen[-self.k] if len(self.seen) >= self.k else None
Python: sorted list with bisect. Correct, O(n) per add.

The optimal approach: a min-heap of size k

Pattern: top-k with a bounded heap. Once k values are held, a new value matters only if it is larger than the smallest of them, which is exactly what a min-heap keeps at the top. So: while the heap has fewer than k items, push. After that, if the new value beats the top, pop the top and push the new value; otherwise ignore it. The top is then the answer.

import heapq

class KthLargest:
    def __init__(self, k, nums):
        self.k = k
        self.heap = []                 # min-heap of the k largest seen so far
        for x in nums:
            self.add(x)

    def add(self, val):
        if len(self.heap) < self.k:
            heapq.heappush(self.heap, val)
        elif val > self.heap[0]:
            heapq.heapreplace(self.heap, val)   # pop smallest, push val
        return self.heap[0] if len(self.heap) == self.k else None
Python: heapq is a min-heap, which is what we want here.
#include <functional>
#include <optional>
#include <queue>
#include <vector>

class KthLargest {
    std::size_t k_;
    // Min-heap: the top is the smallest of the k largest values.
    std::priority_queue<int, std::vector<int>, std::greater<int>> heap_;

public:
    KthLargest(int k, const std::vector<int>& nums) : k_(k) {
        for (int x : nums) add(x);
    }

    std::optional<int> add(int val) {
        if (heap_.size() < k_) {
            heap_.push(val);
        } else if (val > heap_.top()) {
            heap_.pop();
            heap_.push(val);
        }
        if (heap_.size() < k_) return std::nullopt;   // fewer than k seen
        return heap_.top();
    }
};
C++17: priority_queue with std::greater is a min-heap. Returns no value until k numbers have arrived.

Building from the starting list by calling add for each value is O(n log k). An alternative is to heapify the whole list in O(n) and pop until k remain, which is O(n + (n − k) log n); both are fine, and the first keeps the code in one place. In JavaScript there is no built-in heap, so in an interview either write a small binary heap or say which library you would use.

Complexity summary

n values seen so far, heap size at most k
ApproachConstructorEach addSpace
Re-sort on every addO(n log n)O(n log n)O(n)
Sorted list with binary insertO(n log n)O(n)O(n)
Min-heap capped at kO(n log k)O(log k)O(k)
n values seen so far, heap size at most k. Scroll sideways on a small screen.

Common follow-ups

  • Report the running median instead. Keep two heaps: a max-heap for the lower half and a min-heap for the upper half, rebalanced so their sizes differ by at most one. The median is the top of the larger heap, or the average of both tops.
  • Find the kth largest of a fixed array, once. The same size-k heap works in O(n log k), and quickselect averages O(n) with O(n²) worst case; sorting is the simple O(n log n) baseline.
  • Values can also be removed from the stream. A bounded heap no longer works on its own, because a removed value may be one of the k you kept and the replacement may already be gone. Use a balanced search tree or a sorted multiset, or two heaps with lazy deletion.
  • k changes between calls. A heap fixed at size k cannot grow back. Keep all values in an order-statistic structure, such as a tree with subtree sizes, and answer any k in O(log n).
  • Very large streams with many repeats. Store counts per value in the heap or tree to save memory, and remember that the kth largest still counts each repeat.

Edge cases to try

  • A starting list shorter than k, including an empty one.
  • k equal to 1, where the answer is the running maximum.
  • Duplicates: the second-largest of 9, 9, 3 is 9, not 3.
  • New values smaller than everything in the heap, which must not change it.
  • Large positive and negative values, to check nothing overflows or compares as strings.

Pitfalls

  • Using a max-heap of everything and popping k times on each add, which is O(k log n) per call and keeps the whole stream.
  • Letting the heap grow past k by always pushing first and forgetting to pop.
  • Comparing with the top before the heap holds k values, which discards values you still need.
  • Removing duplicates, when the kth largest counts repeated values separately.
  • Writing a JavaScript sort without a comparator, which sorts numbers as strings.

How to explain it out loud

Fictional example

Justifying the min-heap
Candidate
Only the k largest numbers can ever be the answer, so I'll keep just those. The answer is the smallest of them, so I want quick access to the minimum: a min-heap of size k.
Candidate
On each add, if the heap isn't full yet I push. Otherwise, if the new number beats the top, I replace the top. Then the top is the kth largest. That's O(log k) per add and O(k) space.
Candidate
If fewer than k numbers have arrived, I'll return None, unless you'd prefer an error. Duplicates count separately, so I don't dedupe.

A different route to the kth value, this time in a binary search tree that is already ordered, is Kth Smallest Element in a BST. For another structure that answers repeated queries quickly after some upfront work, try Implement Trie.

Practicing it with Natively

Short design questions like this one are often asked in a few minutes at the start of a round, so fluency matters. When you rehearse on Mac or Windows, Natively can read the class description from a screenshot, suggest the heap approach and the questions to ask about small inputs, and transcribe your answer so you can tighten it. More about the AI interview assistant.

Questions people ask

How do you find the kth largest element in a stream?

Keep a min-heap of at most k values. Push while it has fewer than k; after that, replace the top only when a new value is larger. The top of the heap is the kth largest value seen so far.

Why use a min-heap instead of a max-heap?

The answer is the smallest of the k largest values, and a min-heap keeps that value at the top. It also tells you instantly whether a new value is big enough to matter.

What is the time complexity of kth largest in a stream?

O(log k) per add and O(k) space. Building from a starting list of n values by adding each one costs O(n log k).

What if fewer than k numbers have been added?

Many versions promise this never happens when add is called. If it can, decide with the interviewer whether to return nothing, a sentinel or an error, and keep pushing until the heap holds k values.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP