In this blog, we will solve LeetCode Coding Problem ” Kth Largest Element in an Array”. We solve this coding problem by using min heap.
Given an integer array nums
and an integer k
, return the kth
largest element in the array.
Note that it is the kth
largest element in the sorted order, not the kth
distinct element.
Can you solve it without sorting?
1 <= k <= nums.length <= 105
-104 <= nums[i] <= 104
Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
We will solve this coding problem by building heap of size k. Step by step breakdown of solution is as follows.
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int>> minHeap;
for(int i=0; i<nums.size(); i++) {
minHeap.push(nums[i]);
if(minHeap.size() > k) {
minHeap.pop();
}
}
return minHeap.top();
}
};
O(nlogk)
where n = number of elements in array.
O(k)
since we are building a k size min heap.
Thanks for reading and have a nice day.