15% off all plans & roadmaps Use code

See plans

Kth 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 integer k and the initial scores nums.
  • int add(int val) adds the score val to the stream and returns the kth 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^4
  • 1 <= k <= nums.length + 1
  • -10^4 <= nums[i] <= 10^4
  • -10^4 <= val <= 10^4
  • At most 10^4 calls will be made to add.

Constraints that matter

  • k <= nums.length + 1 means that after the first add call there are always at least k scores, so the kth largest always exists when you answer.
  • Up to 10^4 calls to add on 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 add is 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.
  • nums can be empty, so the constructor must work with zero initial scores and still answer correctly after the first add.

View on LeetCode

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.

Watch the pattern animation

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

  1. Store k and a copy of nums in a list.
  2. In add, append val to the list.
  3. Sort the list in ascending order.
  4. 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

TimeO(n log n) per add
SpaceO(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]

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

  1. In the constructor, sort a copy of nums and keep only its k largest values.
  2. In add, binary search for the insertion position of val.
  3. Insert val at that position.
  4. If the list now holds more than k values, remove the first (smallest) one.
  5. 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

TimeO(k) per add
SpaceO(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]
Top K Elements (Selection/Frequency) pattern infographic for Kth Largest Element in a Stream

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

  1. Create an empty min-heap and store k.
  2. For each value in nums, run the same logic as add.
  3. In add, push val onto the heap.
  4. If the heap size is greater than k, pop the smallest value.
  5. Return the root of the heap without removing it.

Dry run

Example: k = 1, nums = [].

StepActionHeap after pushSize > k?Heap after popReturn
initempty 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

TimeO(log k) per add
SpaceO(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

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: pop after 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. If val is smaller than the root, you throw away a valid top-k score. Push first, then pop the smallest.
  • Sorting the list inside add and returning data[k - 1] after an ascending sort. That index is the kth smallest. Use data[len - k] for ascending order.
  • Skipping the initial nums or 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 = 1 with an empty nums: the first add returns the value itself, since the heap holds one element.
  • k = nums.length + 1: the first add brings 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

Practise it