πŸ“ Problem Details

input array nums input integer k return the kth largest element in the array follow up: can you do this without sorting?

πŸ’­What Were My Initial Thoughts?

trivial approach would be to sort the array in descending order and return the k-1th element
class Solution {
public:
Β  Β  int findKthLargest(vector<int>& nums, int k) {
Β  Β  Β  Β  sort(nums.begin(), nums.end(), greater<int>());
Β  Β  Β  Β  return nums[k - 1];
Β  Β  }
};
a more optimized approach could be to use a priority queue or min heap
we keep a min-heap of fixed size k
when the heap exceeds this size we pop

πŸ’‘ Explanation of Solution

  1. Initialize a min-heapΒ heap.
  2. Iterate over the input. For eachΒ num:
    • PushΒ numΒ onto the heap.
    • If the size ofΒ heapΒ exceedsΒ k, pop fromΒ heap.
  3. Return the top of theΒ heap.

βŒ› Complexity Analysis

Time Complexity: O(n log k)
- the limited size of the heap being of size k makes it more efficient than a traditional sort

Space Complexity: O(k)

πŸ’» Implementation of Solution

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        priority_queue<int> pq;
 
        for(int num : nums) {
            pq.push(-num);
            if(pq.size() > k) {
                pq.pop();
            }
        }
        return -pq.top();
    }
};