Data Structures19 sections · 729 units
Open in Course

Kth Largest - Implementation

Complete solution

Here's the solution:

function findKthLargest(nums, k)
    heap := empty min-heap

    for each num in nums
        if size of heap < k
            insert num into heap
        else if num > root of heap
            extract min from heap
            insert num into heap

    return root of heap

Time: O(nlogk)O(n \log k). Space: O(k)O(k).

You'll find this better than sorting when kk is small relative to nn.