Skip to content

Kth Largest Element in an Array

MediumLeetCode #215Time O(n log k)Space O(k)

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 -> 4
sorted descending: 6, 5, 5, 4, ... the 4th entry is 4

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 largest
  • 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.
  • 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] with k = 3 the 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.

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.

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.

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.