TRT
Sign in
mediumCoreLeetCode#size-k min-heap#quickselect

Kth largest element in an array

Find the kth largest value in an unsorted array with a size-k heap or with quickselect, without fully sorting it.

The Runtime Theory Team1 min read
Taught inTop-k and merging streamsPro — members onlyA heap of just k items finds the k largest of a billion in one pass. A heap of k stream heads merges k sorted streams. Two heaps keep a running median. These three patterns cover most heap problems.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innums = [3, 2, 1, 5, 6, 4], k = 2

out5

innums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4

out4

innums = [1], k = 1

out1

Given an array and k, return the kth largest element in sorted order (not the kth distinct one). Try to avoid sorting the whole array.

Before you code

Sorting is O(n log n). Two faster approaches: a min-heap of the k largest seen so far (O(n log k)), or quickselect, which partitions like quick sort but only recurses into one side (O(n) expected).

Hints

  1. Heap: push each value; when the heap exceeds k, pop the smallest. The root is the answer.
  2. Quickselect: the kth largest is at index n − k in sorted order. Partition, then continue only in the side that contains that index.
  3. Use a random pivot for quickselect, or adversarial inputs make it quadratic.

Production & complexity notes

When solving Kth largest element in an array on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Top-k and merging streams to reinforce the underlying pattern.

What it practices

The top-k heap and its alternatives, from Top-k and merging streams.

Not started

Sign in to save your learning progress.

Sign in to save