Algo-Sim › Heaps & Priority Queues

Kth Largest Element in an Array

Medium · Heaps & Priority Queues · step through it in Java, Python and C++ on your own input

Find the kth largest element (counting duplicates) with a min-heap that never holds more than k values.

Problem

Given an integer array nums and k, return the kth largest element in sorted order. Duplicates count separately, so in [3, 3, 1] the 2nd largest is 3.

Constraints

Edge cases to test

Follow-up questions

Can you beat O(n log k)?
Quickselect: partition around a random pivot and recurse on one side, O(n) on average, O(n²) worst case (median of medians makes it O(n) worst case).
What if the data is a stream?
Keep the size-k min-heap; its root is the answer after every value (LC 703).

Solution

Java

public int findKthLargest(int[] nums, int k) {
    PriorityQueue<Integer> heap = new PriorityQueue<>();
    for (int num : nums) {
        heap.offer(num);
        if (heap.size() > k) {
            heap.poll();
        }
    }
    return heap.peek();
}

Python

import heapq


def find_kth_largest(nums, k):
    heap = []
    for num in nums:
        heapq.heappush(heap, num)
        if len(heap) > k:
            heapq.heappop(heap)
    return heap[0]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int findKthLargest(vector<int> &nums, int k) {
        priority_queue<int, vector<int>, greater<int>> heap;
        for (int num : nums) {
            heap.push(num);
            if (int(heap.size()) > k) {
                heap.pop();
            }
        }
        return heap.top();
    }
};

More Heaps & Priority Queues problems