AlgoInsight

DSA problem

Kth Largest Element in a Stream

EasyTop K ElementsPattern: Top K Elementstop150AmazonMicrosoftGoogleBloombergApple

Design a class to find the k-th largest element in a stream of integers. Note that it is the k-th largest element in sorted order, not the k-th distinct element. You must implement a KthLargest class whose constructor accepts an integer k and an initial integer array nums, and an add(val) method that appends val to the stream and returns the element representing the k-th largest element in the stream so far.

The naive way to answer each query is to sort the buffered numbers in descending order and read off index k - 1. That costs O(n log n) every time a new value arrives, which is wasteful because each add call inserts only one element — almost all of the previous structure carries over.

The right structure for this problem is a min-heap of size k. Because the heap holds exactly the top k largest values seen so far, the smallest of those — the heap's root — is precisely the k-th largest in the stream. On every insertion, push the new value, and if the heap now exceeds k elements, pop the smallest. Whatever sits at the root afterwards is the answer.

This design uses O(k) extra space, performs the constructor in O(n log k) time, and answers every add query in O(log k) time. It scales gracefully even as the stream grows to millions of elements, because per-call cost depends only on k, not on the stream length.

Examples

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: After initializing with k=3 and nums=[4,5,8,2], the top-3 are [4,5,8] and the 3rd largest is 4. add(3) keeps the top-3 as [4,5,8] so the answer remains 4. Wait — re-check: add(3) gives stream [4,5,8,2,3], top-3 = [5,8,4] minus the smallest of new top-3 → root = 4. add(5) gives top-3 = [5,5,8], root = 5. add(10) gives top-3 = [5,8,10], root = 5. add(9) gives top-3 = [8,9,10], root = 8. add(4) keeps top-3 = [8,9,10], root = 8.
Example 2
Input: ["KthLargest","add","add","add"] [[1,[]],[-3],[-2],[-4]]
Output: [null,-3,-2,-2]
Explanation: With k=1, the answer is always the maximum of the stream. After -3 it is -3, after -2 it is -2, and -4 does not change the maximum.
Example 3
Input: ["KthLargest","add","add"] [[2,[0]],[1],[2]]
Output: [null,0,1]
Explanation: With k=2, after one add the heap fills to size 2 (root = 0); the next add pushes 2 and evicts 0, making the root 1.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

heappriority-queuedesignstreamtop-k

Browse all DSA problems