Kth Largest Element in an Array

Medium ArrayDivide and ConquerSortingHeap (Priority Queue)Quickselect

Approaches

?

Insight Challenge

Why do we use a min-heap of size k instead of a max-heap?

Maintain only the top k candidates as we scan

Instead of sorting everything, we can maintain a collection of the k largest elements seen so far. The smallest element in this collection is our answer—if a new element is smaller than our current kth largest, it can't possibly be in the top k. A min-heap naturally surfaces the smallest element for efficient comparison and replacement.

Algorithm

  1. Create an empty collection to hold candidates
  2. Process each element in the array:
  3. Add the element to our candidate collection
  4. If we have more than k candidates, remove the smallest
  5. The smallest remaining candidate is the kth largest overall

Solution

Time O(n log k) Space O(k)
def find_kth_largest(nums, k):
    import heapq
    min_heap = []
    for num in nums:
        heapq.heappush(min_heap, num)
        if len(min_heap) > k:
            heapq.heappop(min_heap)
    return min_heap[0]
ByteLingo

See algorithms come alive.

© 2026 ByteLingo