← Back to Algorithms, page 3

algorithms-0046 · Medium mid

Find the k-th largest element in an unsorted list without fully sorting it, using a heap and using quickselect.

A min-heap of size k keeps the k largest values seen; its top is the k-th largest. That costs O(n log k) time and O(k) space and works on streams. Quickselect partitions like quicksort but recurses only into the side containing the target index, giving O(n) average time with a random pivot, O(n^2) in the worst case.

Full answer

Problem

Given nums and k, return the k-th largest value (counting duplicates; for [3, 2, 3, 1, 2, 4, 5, 5, 6] and k = 4 the answer is 4).

Example: [3, 2, 1, 5, 6, 4], k = 2 gives 5.

Constraints: 1 <= k <= len(nums) <= 10^5. The quickselect version raises ValueError for an invalid k.

Brute force

Sort descending and take index k - 1: O(n log n). Simple and often fine; interviewers then ask for something faster.

Optimal approach

Heap:

  1. Push each value onto a min-heap.
  2. If the heap holds more than k values, pop the smallest.
  3. At the end the heap holds the k largest; heap[0] is the k-th largest.

Quickselect:

  1. Target index in ascending order: len(nums) - k.
  2. Partition around a random pivot (Lomuto); the pivot lands at index i.
  3. If i == target, return it; if i < target, continue on the right part; otherwise the left part.

Why it works

Heap: the invariant is "the heap contains the k largest values seen so far". A new value either enters, pushing out the smallest of the k + 1, or is too small. The smallest of the k largest is the k-th largest.

Quickselect: after partitioning, the pivot is in its final sorted position. The target is on exactly one side, so the other side can be ignored. With a random pivot the part shrinks by a constant factor on average, so the total work is about n + n/2 + n/4 + ... = O(n).

Complexity

Heap: O(n log k) time, O(k) space. Quickselect: O(n) average, O(n^2) worst, O(n) space here because it copies the input to avoid changing it (O(1) extra if done in place). Median of medians guarantees O(n) worst case but is slower in practice.

Code

python
import heapq
import random


def kth_largest_heap(nums, k):
    """Keep a min-heap of the k largest values seen. O(n log k) time, O(k) space."""
    heap = []
    for x in nums:
        heapq.heappush(heap, x)
        if len(heap) > k:
            heapq.heappop(heap)          # drop the smallest of the k + 1
    return heap[0]


def kth_largest_quickselect(nums, k, seed=7):
    """Average O(n), worst O(n^2) (made unlikely by a random pivot). Copies the input."""
    if not 1 <= k <= len(nums):
        raise ValueError("need 1 <= k <= len(nums)")
    rng = random.Random(seed)
    a = list(nums)
    target = len(a) - k                  # index of the answer in ascending order
    lo, hi = 0, len(a) - 1
    while True:
        p = rng.randint(lo, hi)
        a[p], a[hi] = a[hi], a[p]
        pivot, i = a[hi], lo
        for j in range(lo, hi):
            if a[j] < pivot:
                a[i], a[j] = a[j], a[i]
                i += 1
        a[i], a[hi] = a[hi], a[i]
        if i == target:
            return a[i]
        if i < target:
            lo = i + 1
        else:
            hi = i - 1


if __name__ == "__main__":
    for f in (kth_largest_heap, kth_largest_quickselect):
        assert f([3, 2, 1, 5, 6, 4], 2) == 5
        assert f([3, 2, 3, 1, 2, 4, 5, 5, 6], 4) == 4
        assert f([1], 1) == 1
        assert f([2, 2, 2], 2) == 2
        assert f([-1, -5, 0], 3) == -5
    try:
        kth_largest_quickselect([1, 2], 3)
        raise AssertionError("expected ValueError")
    except ValueError:
        pass
    print("all tests passed")

Save as a46_kth_largest.py and run python3 a46_kth_largest.py. It prints all tests passed (Python 3.13.5).

Edge cases

k = 1 (maximum) and k = n (minimum). Duplicates count separately. Negative values. All values equal. Invalid k is rejected by the quickselect version. heapq.nlargest(k, nums)[-1] is a one-line library option.

Pattern

Top-k selection with a bounded heap, and partition-based selection. Related: top k frequent elements, k closest points to the origin, and a running median with two heaps.

python
import heapq
import random


def kth_largest_heap(nums, k):
    """Keep a min-heap of the k largest values seen. O(n log k) time, O(k) space."""
    heap = []
    for x in nums:
        heapq.heappush(heap, x)
        if len(heap) > k:
            heapq.heappop(heap)          # drop the smallest of the k + 1
    return heap[0]


def kth_largest_quickselect(nums, k, seed=7):
    """Average O(n), worst O(n^2) (made unlikely by a random pivot). Copies the input."""
    if not 1 <= k <= len(nums):
        raise ValueError("need 1 <= k <= len(nums)")
    rng = random.Random(seed)
    a = list(nums)
    target = len(a) - k                  # index of the answer in ascending order
    lo, hi = 0, len(a) - 1
    while True:
        p = rng.randint(lo, hi)
        a[p], a[hi] = a[hi], a[p]
        pivot, i = a[hi], lo
        for j in range(lo, hi):
            if a[j] < pivot:
                a[i], a[j] = a[j], a[i]
                i += 1
        a[i], a[hi] = a[hi], a[i]
        if i == target:
            return a[i]
        if i < target:
            lo = i + 1
        else:
            hi = i - 1


if __name__ == "__main__":
    for f in (kth_largest_heap, kth_largest_quickselect):
        assert f([3, 2, 1, 5, 6, 4], 2) == 5
        assert f([3, 2, 3, 1, 2, 4, 5, 5, 6], 4) == 4
        assert f([1], 1) == 1
        assert f([2, 2, 2], 2) == 2
        assert f([-1, -5, 0], 3) == -5
    try:
        kth_largest_quickselect([1, 2], 3)
        raise AssertionError("expected ValueError")
    except ValueError:
        pass
    print("all tests passed")

Bounded min-heap version and seeded quickselect (random.Random(7)) that copies the input; both pass the same tests.

Complexity

Time: Heap O(n log k); quickselect O(n) average, O(n^2) worst. Space: Heap O(k); quickselect O(n) for the copy. Median of medians gives a worst-case O(n) selection.

By level

Fresher: Implements the size-k min-heap and explains why its top is the answer. Should give the sort-based baseline first.

Mid: Adds quickselect with a random pivot and compares the two on time, space and streaming use. States the target index formula for quickselect.

Senior: Discusses worst-case guarantees with median of medians, distributed top-k and approximate methods for very large data. Can explain why the heap version suits streams better than quickselect.

Key points

  • Min-heap of size k keeps the k largest
  • Heap top is the answer
  • Quickselect only follows the side with the target
  • Target index is n - k in ascending order
  • Heap works on streams; quickselect needs all data

Common mistakes

  • Using a max-heap of all n values and calling it O(n log k)
  • Off-by-one between k-th largest and index
  • Forgetting that quickselect has an O(n^2) worst case
  • Removing duplicates when they should count

Follow-ups

  • How would you find the k-th largest in a stream?
  • How do you get the k closest points to a location?
  • What is median of medians?

Tips

  • Give the sort solution and its cost first
  • Compare heap and quickselect trade-offs
  • State the target index formula

Evaluation rubric

  • Correct heap or quickselect implementation
  • Correct complexity for both
  • Handles duplicates and k bounds
  • Discusses trade-offs