Kth Largest Element in an Array
The problem
Section titled “The problem”You get an unsorted integer array and a number k. Return the kth largest element in
sorted order, not the kth distinct one. Duplicates count separately.
nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4 -> 4sorted descending: 6, 5, 5, 4, ... the 4th entry is 4Key insight
Section titled “Key insight”Sorting works and is O(n log n), but it orders everything when you only need one position. The waste is tracking the elements that are too small to matter.
Keep a min-heap that never holds more than k items: the k largest seen so far. When it grows to k + 1, pop the smallest, because it can’t be the kth largest anymore. At the end the root is the smallest of the top k, which is exactly the kth largest. Each push or pop costs O(log k), not O(log n).
Show solutionHide solution
import heapq
def find_kth_largest(nums: list[int], k: int) -> int: heap = [] # min-heap holding the k largest values seen so far for num in nums: heapq.heappush(heap, num) if len(heap) > k: heapq.heappop(heap) # evict the smallest; it can't be the kth largest return heap[0] # smallest of the k largest = kth largestexport function findKthLargest(nums: number[], k: number): number { // Heap: a standard binary heap (LeetCode provides MinPriorityQueue) const heap = new Heap<number>((a, b) => a - b); // min-heap of the k largest so far for (const num of nums) { heap.push(num); if (heap.size > k) heap.pop(); // evict the smallest } return heap.peek()!; // smallest of the k largest = kth largest}import java.util.PriorityQueue;
class Solution { public int findKthLargest(int[] nums, int k) { PriorityQueue<Integer> heap = new PriorityQueue<>(); // min-heap of the k largest so far for (int num : nums) { heap.offer(num); if (heap.size() > k) heap.poll(); // evict the smallest } return heap.peek(); // smallest of the k largest = kth largest }}Complexity
Section titled “Complexity”- Time: O(n log k) — n elements, each causing at most one push and one pop on a heap of size k.
- Space: O(k) — the heap never holds more than k + 1 items.
Watch out for
Section titled “Watch out for”- Min-heap, not max-heap. For the kth largest, the heap root must be the item you can throw away, which is the smallest of the keepers.
- Duplicates count. In
[5, 5, 5, 1]withk = 3the answer is 5. Don’t dedupe. - Quickselect is the other answer. It averages O(n) time and O(1) extra space, but the worst case is O(n²) (random pivots make it unlikely, not impossible), and it modifies the input. Mention it, then code the heap unless asked.
- JS/TS interviews. There is no built-in heap. Say you will assume a heap helper
exists (LeetCode gives you
MinPriorityQueue) and offer to implement it.
Variations
Section titled “Variations”Kth Largest Element in a Stream (LeetCode 703)
Section titled “Kth Largest Element in a Stream (LeetCode 703)”Numbers keep arriving and you must report the kth largest after each one. The trick:
the same size-k min-heap, kept alive between calls. Each add pushes, pops if the size
exceeds k, and returns the root.
K Closest Points to Origin (LeetCode 973)
Section titled “K Closest Points to Origin (LeetCode 973)”Return the k points nearest (0, 0). The trick: keep a size-k max-heap keyed by
squared distance, so the farthest keeper is on top and gets evicted. Skip the square root.
Last Stone Weight (LeetCode 1046)
Section titled “Last Stone Weight (LeetCode 1046)”Repeatedly smash the two heaviest stones together until at most one is left. The trick: a max-heap. Pop two, push back their difference if it is non-zero. In Python, negate the values.