</>

215. Kth Largest Element in an Array

Medium NeetCode 150
Heap / Priority Queue Time O(N) Space O(1)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Heap / Priority Queue
Time
O(N)
Space
O(1)

Standard Solution (C++)

SummaryGiven an unsorted integer array, find the value of the element that ranks k-th from the top (i.e., the k-th largest value when the array is sorted in descending order).

Approach
  • Maintain a min-heap of size k: push each element, then pop the minimum whenever the heap exceeds k elements.
  • After processing all elements, the heap's top is the smallest among the k largest values — which is exactly the k-th largest overall.
  • This avoids full sorting and keeps memory bounded to O(k) at all times.
  • Time cost is O(n log k) because each of the n pushes/pops touches a heap of height log k.
#include <vector>
#include <queue>
using namespace std;

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        // Min-heap: always expel the smallest so only the k largest remain.
        priority_queue<int, vector<int>, greater<int>> minHeap;

        for (int num : nums) {
            minHeap.push(num);
            if ((int)minHeap.size() > k) {
                minHeap.pop(); // remove the current minimum
            }
        }

        // Top of the min-heap is the k-th largest element.
        return minHeap.top();
    }
};
Time O(n log k) Space O(k)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

#include <vector>
using namespace std;

class Solution {
public:
    int quickSelect(vector<int>& nums, int l, int r) {
        int randomIdx=std::rand()%(r-l+1)+l;
        swap(nums[randomIdx], nums[r]);
        int pivot=nums[r];
        int i=l;
        for(int j=l; j<r; ++j){
            if(nums[j]>pivot){
                swap(nums[i], nums[j]); // keep larger nums at the left
                ++i;
            }
        }
        swap(nums[i], nums[r]);
        return i;
    }
    int findKthLargest(vector<int>& nums, int k) {
        srand(time(NULL));
        
        int n=nums.size();
        int target=k-1;

        int l=0, r=n-1;
        while(l<=r){
            int pidx=quickSelect(nums, l, r);
            if(pidx==target){
                return nums[pidx];
            }
            else if(pidx<target){
                l=pidx+1;
            }
            else{ // p>target
                r=pidx-1;
            }
        }

        return nums[l];
    }
};

// Time Complexity: O(N) on average, O(N^2) in the worst case (when the smallest or largest element is always chosen as the pivot).
// Space Complexity: O(1) for the in-place partitioning.
Time O(N) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern