Intermediate Level

Implement the kthLargestElementHeap method that returns the kth largest value using heap logic.

The input array nums contains size integers, and k specifies the required position.

Your task is to return the kth largest element in the array. The value is based on sorted order, not on distinct values.

For example, in [3,2,1,5,6,4] with k = 2, the second largest element is 5.

Example 1

Input
nums (int[]) = [3,2,1,5,6,4]
size (int) = 6
k (int) = 2
Returns (int) 5

Example 2

Input
nums (int[]) = [3,2,3,1,2,4,5,5,6]
size (int) = 9
k (int) = 4
Returns (int) 4

Example 3

Input
nums (int[]) = [1]
size (int) = 1
k (int) = 1
Returns (int) 1

Use a min heap of size k.

Insert values into the heap. If the heap size becomes greater than k, remove the smallest value from the heap. This keeps only the largest k values seen so far.

After all values are processed, the top of the min heap is the kth largest element.

Pseudocode:

function kthLargestElementHeap(nums, size, k):
    create empty minHeap
    for each value in nums:
        push value into minHeap
        if heap size > k:
            remove smallest value from minHeap
    return top of minHeap
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.