Skip to main content

Top-K Elements

A recurring pattern in interviews — finding the K largest, smallest, or most frequent elements.

Approaches

1. Sorting

Sort the collection and pick the first/last K elements.
  • Time: O(n log n)
  • Simple but not optimal

2. Min/Max Heap of Size K

Maintain a heap of size K:
  • K largest → use a min-heap of size K (pop smallest when size exceeds K)
  • K smallest → use a max-heap of size K
  • Time: O(n log k)
  • Space: O(k)

3. Quickselect

Partition-based selection (like quicksort but only recurse on one side).
  • Time: O(n) average, O(n²) worst
  • Space: O(1)
  • Best when you need the k-th element, not all top K sorted

4. Bucket Sort (for frequency problems)

When finding top K by frequency, bucket sort avoids heap overhead:
  • Time: O(n)

Which Approach to Use

Classic Problems

  • Kth Largest Element in an Array
  • Top K Frequent Elements
  • Top K Frequent Words
  • K Closest Points to Origin
  • Find K Pairs with Smallest Sums
  • Sort Characters by Frequency
  • Reorganize String
  • K Closest Elements in Sorted Array