Problem

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Implement the KthLargest class:

  • KthLargest(int k, int[] nums) initializes the object with the integer k and the stream of integers nums

  • int add(int val) appends the integer val to the stream and returns the element representing the kth largest element in the stream.

Source: https://leetcode.com/problems/kth-largest-element-in-a-stream

Constraints

  • 1 <= k <= 10^4
  • 0 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • -10^4 <= val <= 10^4
  • At most 10^4 calls will be made to add
  • It is guaranteed that there will be at least k elements in the array when you search for the kth element

Asymptotic Complexity

  • Time: O(nlogn), details:
    • O(logn) per new value added
    • O(1) to get the kth largest value
  • Space: O(k)

Strategy

  • Uses a min-heap data structure
  • Only adds the kth largest values to it
  • By ignoring the remaining, smaller values, the kth largest value is always the topmost value
  • This avoids random access and can reduce some memory costs

Setup

  • Create a min-heap using the k largest values only
  • Add INT_MIN to the heap as a temporary placeholder when nums has k - 1 items

Adding New Values

  • Only add values larger than the kth value
  • Push the larger value on the heap
  • Remove the old, kth largest value
  • Return the new, kth largest value

Implementation

class KthLargest {
public:
    KthLargest(int k, vector<int>& nums) {
        //Load the Kth largst values onto a min-heap:
        for (auto n : nums) {
            if (_minHeap.size() < k || n > _minHeap.top()) {
                _minHeap.push(n);
                if (_minHeap.size() > k) {
                    _minHeap.pop();
                }
            }
        }

        //Pad if required:
        while (_minHeap.size() < k) {
            _minHeap.push(INT_MIN);
        }
    }

    int add(int val) {
        if (val > _minHeap.top()) {
            //Add the new value:
            _minHeap.push(val);

            //Remove the smallest:
            _minHeap.pop();
        }

        //Return the Kth smallest:
        return _minHeap.top();
    }

private:
    priority_queue<int, vector<int>, greater<int>> _minHeap; 
};

Categories:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *