KatInterview

789. Kth Largest Element in a Stream

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to design a class, KthLargest, to find the kth largest element in a constantly growing stream of numbers. We are given an initial set of numbers and a value k. The main challenge is to efficiently handle the add operation, which introduces a new number to the stream and requires us to find the new kth largest element without reprocessing the entire set of numbers each time. A naive approach of sorting the entire list on every add call would be too slow, leading to a time complexity of O(N log N) for each addition, where N is the current size of the stream.

Solution

Kth Largest Element in a Stream in Python

import heapq
from typing import List

class KthLargest:

    def __init__(self, k: int, nums: List[int]):
        # Store k and initialize a min-heap (list in Python used with heapq).
        self.k = k
        self.heap = []
        # Process the initial stream of numbers by calling the add method.
        for num in nums:
            self.add(num)

    def add(self, val: int) -> int:
        # If the heap has less than k elements, we can add the new element.
        # The heap will maintain the k largest elements seen so far.
        if len(self.heap) < self.k:
            heapq.heappush(self.heap, val)
        # If the new value is greater than the smallest element in the heap
        # (which is at the top of the min-heap), it deserves a place in
        # our set of k largest elements.
        elif val > self.heap[0]:
            # heapq.heappushpop is an efficient way to push a new item and
            # then pop the smallest item.
            heapq.heappushpop(self.heap, val)
        
        # The top of our min-heap (self.heap[0]) is the kth largest element.
        return self.heap[0]


# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)

Kth Largest Element in a Stream in Java

import java.util.PriorityQueue;

class KthLargest {
    // A min-heap (PriorityQueue in Java is a min-heap by default) 
    // to store the k largest elements.
    private PriorityQueue<Integer> minHeap;
    private int k;

    public KthLargest(int k, int[] nums) {
        this.k = k;
        this.minHeap = new PriorityQueue<>();
        
        // Process the initial numbers by calling the add method.
        // This populates the heap with the k largest elements from the initial array.
        for (int num : nums) {
            add(num);
        }
    }
    
    public int add(int val) {
        // If the heap has fewer than k elements, we can add the new element directly.
        if (minHeap.size() < k) {
            minHeap.offer(val);
        } 
        // If the new value is larger than the smallest element currently in the heap
        // (which is the kth largest element overall, found at minHeap.peek()), we should replace it.
        else if (val > minHeap.peek()) {
            minHeap.poll(); // Remove the current kth largest (the smallest in the heap)
            minHeap.offer(val); // Add the new, larger value
        }
        
        // The root of the min-heap is the kth largest element.
        return minHeap.peek();
    }
}

/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest obj = new KthLargest(k, nums);
 * int param_1 = obj.add(val);
 */

Kth Largest Element in a Stream in C++

class KthLargest {
private:
    // A min-heap to store the k largest elements.
    // The top of the min-heap is the kth largest element.
    // In C++, priority_queue is a max-heap by default. We use `greater<int>` to make it a min-heap.
    std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap;
    int size_k;

public:
    KthLargest(int k, std::vector<int>& nums) {
        size_k = k;
        // Process the initial numbers by calling our add method.
        // This ensures the heap is correctly initialized with the k largest elements from the start.
        for (int num : nums) {
            add(num);
        }
    }
    
    int add(int val) {
        // If the heap has less than k elements, just add the new value.
        if (minHeap.size() < size_k) {
            minHeap.push(val);
        } 
        // If the new value is greater than the smallest element in the heap (the top),
        // it means the new value should be in the set of top k elements.
        else if (val > minHeap.top()) {
            minHeap.pop(); // Remove the smallest of the current k largest.
            minHeap.push(val); // Add the new larger value.
        }
        
        // The top of the min-heap is always the kth largest element once the heap has k elements.
        return minHeap.top();
    }
};

/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest* obj = new KthLargest(k, nums);
 * int param_1 = obj->add(val);
 */

Kth Largest Element in a Stream in TypeScript

class KthLargest {
    private k: number;
    // We use an array to implement the min-heap manually since TS/JS doesn't have a native one.
    private heap: number[];

    constructor(k: number, nums: number[]) {
        this.k = k;
        this.heap = [];
        
        // Process initial numbers by calling the add method.
        for (const num of nums) {
            this.add(num);
        }
    }

    public add(val: number): number {
        // If heap size is less than k, add the element.
        if (this.heap.length < this.k) {
            this.push(val);
        } 
        // If the new element is larger than the smallest in the heap (the top),
        // replace the top and restore heap property.
        else if (val > this.heap[0]) {
            // This is an efficient 'pushpop' operation.
            this.heap[0] = val;
            this.siftDown(0);
        }
        
        // The top of the heap is the kth largest element.
        return this.heap[0];
    }

    // --- Min-Heap Helper Methods ---

    private parent(i: number): number { return Math.floor((i - 1) / 2); }
    private left(i: number): number { return 2 * i + 1; }
    private right(i: number): number { return 2 * i + 2; }
    private swap(i: number, j: number): void {
        [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
    }

    private push(val: number): void {
        this.heap.push(val);
        this.siftUp(this.heap.length - 1);
    }

    private siftUp(i: number): void {
        // Move an element up the heap until it's in the correct position.
        while (i > 0 && this.heap[this.parent(i)] > this.heap[i]) {
            this.swap(i, this.parent(i));
            i = this.parent(i);
        }
    }

    private siftDown(i: number): void {
        // Move an element down the heap until it's in the correct position.
        let minIndex = i;
        const l = this.left(i);
        if (l < this.heap.length && this.heap[l] < this.heap[minIndex]) {
            minIndex = l;
        }
        const r = this.right(i);
        if (r < this.heap.length && this.heap[r] < this.heap[minIndex]) {
            minIndex = r;
        }
        if (i !== minIndex) {
            this.swap(i, minIndex);
            this.siftDown(minIndex);
        }
    }
}

/**
 * Your KthLargest object will be instantiated and called as such:
 * var obj = new KthLargest(k, nums)
 * var param_1 = obj.add(val)
 */

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.