BackendML

Kth Largest Element in a Stream

Medium2 min read
The Kth Largest Element in a Stream problem requires continuously maintaining the kth largest value as new numbers are added to a stream.

Problem

Given an integer k and a stream of integers, design a class that returns the kth largest element whenever a new value is added to the stream.

The stream can contain duplicate values, and the kth largest element is based on all values seen so far.

Example(s)

Consider the following examples to understand the expected input and output.

Example 1

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

add(3)
add(5)
add(10)
add(9)
add(4)
Output
4
5
5
8
8

Example 2

Input
k = 1
nums = [3,1,5,2]

add(4)
add(6)
Output
4
6

Solution

This solution uses a Min Heap to maintain the k largest elements seen so far. Java's PriorityQueue is a min heap by default.

Whenever a new value is added, we insert it into the heap. If the heap size becomes greater than k, we remove the smallest element. Therefore, the heap always contains the k largest elements, and the element at the root is the kth largest element.
class KthLargest {

    private final int k;
    private final PriorityQueue<Integer> minHeap;

    public KthLargest(int k, int[] nums) {
        this.k = k;
        this.minHeap = new PriorityQueue<>();

        for (int num : nums) {
            add(num);
        }
    }

    public int add(int val) {
        minHeap.offer(val);

        if (minHeap.size() > k) {
            minHeap.poll();
        }
        return minHeap.peek();
    }
}

Complexity

For the initial n elements, each insertion takes O(log k) time, giving an overall time complexity of O(n log k). Each subsequent add() operation takes O(log k) time.

The min heap stores at most k elements, so the extra space complexity is O(k).

Comments

No comments yet. Ask a question or share what helped.