~/DHRUVUpskilling
← board/DSA/Top K Elements/dsa-top-k-elements-01
Backlog·queued

Kth Largest Element in an Array

DifficultyMedium
PatternTop K Elements
TrackDSA
tl;dr

Given an integer array nums and an integer k, return the kth largest element in the array.

full write-up

Note that it is the kth largest element in the sorted order, not the kth distinct element.

Can you solve it without sorting?

Example 1:

Input: nums = [3,2,1,5,6,4], k = 2 Output: 5 Example 2:

Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 Output: 4

Solution

To solve this type of question related to kth term we try to maintain heap size of k. If question asks for max k element we create a min heap opposite and we'll push first k value of arr into min heap. now we'll check rest of the values if they are smaller than peek this value cannot be our largest kth value so we ignore that else we pop peek and insert new value.


var findKthLargest = function(nums, k) {
    let heap= new NewMinHeap();

    for (let i=0; i<k; i++){

        heap.push(nums[i])
    }

    for(let i=k; i<nums.length; i++){
        if(nums[i]>heap.peek()){
            heap.pop();
            heap.push(nums[i])
        }
    }

    return heap.peek()
};