Algo-Sim › Heaps & Priority Queues

Kth Largest Element in a Stream

Easy · Heaps & Priority Queues · step through it in Java, Python and C++ on your own input

Answer "what is the kth largest so far?" after every new value. A min-heap that never holds more than k values keeps the answer at its root.

Problem

Design a class KthLargest. Its constructor receives k and an initial array nums. Each call add(val) appends val to the stream and returns the kth largest value seen so far (duplicates count separately).

Constraints

Edge cases to test

Follow-up questions

Why a min-heap for the largest values?
The root is the smallest of the k largest, which is exactly the k-th largest, and it is the one to evict: O(log k) per add.
What if k changes per query?
Use an order-statistics tree (or a Fenwick tree over value ranks): O(log n) per insert and per k-th query.

Solution

Java

class KthLargest {
    private final PriorityQueue<Integer> heap = new PriorityQueue<>();
    private final int k;

    public KthLargest(int k, int[] nums) {
        this.k = k;
        for (int num : nums) add(num);
    }

    public int add(int val) {
        heap.offer(val);
        if (heap.size() > k) {
            heap.poll();
        }
        return heap.peek();
    }
}

Python

import heapq


class KthLargest:
    def __init__(self, k, nums):
        self.k = k
        self.heap = []
        for num in nums:
            self.add(num)

    def add(self, val):
        heapq.heappush(self.heap, val)
        if len(self.heap) > self.k:
            heapq.heappop(self.heap)
        return self.heap[0]

C++

#include <bits/stdc++.h>
using namespace std;

class KthLargest {
  public:
    priority_queue<int, vector<int>, greater<int>> heap;
    int k;

    KthLargest(int k, vector<int> &nums) {
        this->k = k;
        for (int num : nums) {
            add(num);
        }
    }

    int add(int val) {
        heap.push(val);
        if (int(heap.size()) > k) {
            heap.pop();
        }
        return heap.top();
    }
};

More Heaps & Priority Queues problems