Medium
Heap / Priority Queue
Kth Largest Element in an Array
A size-k min-heap keeps exactly the k largest seen so far.
Approach
Push elements into a min-heap; once it exceeds size k, pop the smallest. After the pass, the heap's root is the kth largest. Quickselect gives an average O(n) alternative by partitioning around a pivot without fully sorting.
Time complexity
O(n log k) heap / O(n) quickselect avg
Space complexity
O(k)
Common mistake
Fully sorting the array (O(n log n)) when a k-sized heap or quickselect is faster.
See it run, step by step
Generate an interactive lesson for Kth Largest Element in an Array — trace every variable and watch the algorithm execute until it clicks.
Start a lesson on Kth Largest Element in an Array