algoadvance

Leetcode 703. Kth Largest Element in a Stream

Problem Statement

You need to design a class to find the Kth largest element in a stream. The class should have the following components:

Clarifying Questions

  1. Is the input array nums always sorted?
    • No, nums may be unsorted.
  2. Can nums be empty?
    • Yes, nums can be empty.
  3. Can k be greater than the length of nums?
    • Yes, k can be greater than the length of nums. At any point in time, if the number of elements in the list is less than k, the Kth largest element will be the smallest value (INT_MIN can be used in this implementation).

Strategy

To efficiently manage the Kth largest element in a stream, use a min-heap (priority queue in C++). The heap will have a size of at most k.

This ensures that the heap contains the k largest elements seen so far, with the smallest of these k elements at the top, which is the Kth largest element.

Code

#include <vector>
#include <queue>
#include <algorithm>

class KthLargest {
private:
    int k;
    std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap;
    
public:
    KthLargest(int k, std::vector<int>& nums) {
        this->k = k;
        for (int num : nums) {
            add(num);
        }
    }
    
    int add(int val) {
        if (minHeap.size() < k) {
            minHeap.push(val);
        } else if (val > minHeap.top()) {
            minHeap.pop();
            minHeap.push(val);
        }
        return minHeap.top();
    }
};

Time Complexity

This approach ensures efficient handling of each new element while maintaining the kth largest result.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI