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
- 1 ≤ k ≤ nums.length ≤ 10⁵
- -10⁴ ≤ nums[i] ≤ 10⁴
- Can you beat a full O(n log n) sort?
Edge cases to test
- k = 1 (the maximum) and k = n (the minimum)
- Duplicates count separately
- Negative values
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
- Kth Largest Element in a Stream (Easy)
- Merge K Sorted Lists (Hard)
- Find Median from Data Stream (Hard)
- Find K Pairs with Smallest Sums (Medium)
- Heap Sort (Build Heap + Sift Down) (Medium)
- Last Stone Weight (Easy)
- K Closest Points to Origin (Medium)
- Top K Frequent Words (Medium)
- Reorganize String (Medium)
- IPO (Hard)