Kth Largest Element in an Array

mediumHeap / Priority Queue30 stepsJava · Python · C++

Keep a min-heap of the k largest values seen so far. Push each number; if the heap grows past k, pop its smallest. At the end the heap's top is the k-th largest.

▶ Watch the animated trace

Traced input: nums = [3, 2, 1, 5, 6, 4], k = 2 → 5. Original problem: neetcode.io/problems/kth-largest-element-in-an-array

Complexity

BestO(n log k)
AverageO(n log k)
WorstO(n log k)
SpaceO(k)

Quickselect is O(n) on average, O(n²) worst case.

Key idea

Common mistakes

Solution

Java
int findKthLargest(int[] nums, int k) {
    PriorityQueue<Integer> heap = new PriorityQueue<>();
    for (int i = 0; i < nums.length; i++) {
        heap.offer(nums[i]);
        if (heap.size() > k) {
            heap.poll();
        }
    }
    return heap.peek();
}
Python
def findKthLargest(nums: List[int], k: int) -> int:
    heap = []
    for x in nums:
        heapq.heappush(heap, x)
        if len(heap) > k:
            heapq.heappop(heap)
    return heap[0]
C++
int findKthLargest(vector<int>& nums, int k) {
    priority_queue<int, vector<int>, greater<int>> heap;
    for (int x : nums) {
        heap.push(x);
        if ((int)heap.size() > k) {
            heap.pop();
        }
    }
    return heap.top();
}

Edge cases

Each one has its own trace in the interactive view.

CaseInputAnswer
Duplicates
6, 5, 5, 4: the two 5s count separately.
nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 44
k = 1
The maximum.
nums = [7, 2, 9], k = 19
k = n
The minimum.
nums = [7, 2, 9], k = 32
Negatives
Ordering works the same.
nums = [-1, -5, -3], k = 2-3
← Serialize and Deserialize Binary TreeLast Stone Weight →