Top K Elements
Find the k largest, smallest, most frequent or closest items with a size-k heap, bucket sort or quickselect.
"Find the k largest / smallest / most frequent / closest" is one of the most common interview patterns. Sorting all n items costs O(n log n). A heap of size k costs O(n log k), and the expected-O(n) quickselect is faster still.
- The words top k, k largest/smallest, k most frequent, k closest, kth.
- Streaming data where you can only keep k items in memory.
- Rearranging items so the same value never lands next to itself (reorganise string, task scheduler): a max-heap by count.
The counter-intuitive trick
To keep the k largest, use a min-heap of size k. The heap's top is the smallest of the current top k, so it is the one to evict when something bigger arrives. When you finish, the top is the kth largest.
int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>(); // min-heap
for (int x : nums) {
heap.offer(x);
if (heap.size() > k) heap.poll(); // evict the smallest
}
return heap.peek();
}import heapq
def find_kth_largest(nums, k):
heap = []
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap)
return heap[0]
# or: heapq.nlargest(k, nums)[-1]function findKthLargest(nums: number[], k: number): number {
const heap = new Heap<number>((a, b) => a - b); // min-heap
for (const x of nums) {
heap.push(x);
if (heap.size > k) heap.pop();
}
return heap.peek()!;
}Top k frequent: bucket sort in O(n)
Frequencies are between 1 and n, so put each value in bucket[freq] and read the buckets from high to low.
int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> freq = new HashMap<>();
for (int x : nums) freq.merge(x, 1, Integer::sum);
List<Integer>[] bucket = new List[nums.length + 1];
for (var e : freq.entrySet()) {
if (bucket[e.getValue()] == null) bucket[e.getValue()] = new ArrayList<>();
bucket[e.getValue()].add(e.getKey());
}
int[] res = new int[k];
int i = 0;
for (int f = nums.length; f > 0 && i < k; f--)
if (bucket[f] != null) for (int x : bucket[f]) if (i < k) res[i++] = x;
return res;
}from collections import Counter
def top_k_frequent(nums, k):
bucket = [[] for _ in range(len(nums) + 1)]
for x, f in Counter(nums).items():
bucket[f].append(x)
res = []
for f in range(len(nums), 0, -1):
res.extend(bucket[f])
if len(res) >= k:
return res[:k]
# heap alternative: heapq.nlargest(k, cnt, key=cnt.get)function topKFrequent(nums: number[], k: number): number[] {
const freq = new Map<number, number>();
for (const x of nums) freq.set(x, (freq.get(x) ?? 0) + 1);
const bucket: number[][] = Array.from({ length: nums.length + 1 }, () => []);
for (const [x, f] of freq) bucket[f].push(x);
const res: number[] = [];
for (let f = nums.length; f > 0 && res.length < k; f--) res.push(...bucket[f]);
return res.slice(0, k);
}Quickselect: expected O(n)
Partition like quicksort, but recurse only into the side that contains index n − k. Randomise the pivot to avoid the O(n²) worst case. (Details: Searching.)
int quickselect(int[] a, int k) { // kth largest
int target = a.length - k, lo = 0, hi = a.length - 1;
Random rnd = new Random();
while (true) {
int p = lo + rnd.nextInt(hi - lo + 1);
swap(a, p, hi);
int store = lo;
for (int i = lo; i < hi; i++) if (a[i] < a[hi]) swap(a, i, store++);
swap(a, store, hi);
if (store == target) return a[store];
if (store < target) lo = store + 1; else hi = store - 1;
}
}import random
def quickselect(a, k):
target, lo, hi = len(a) - k, 0, len(a) - 1
while True:
p = random.randint(lo, hi)
a[p], a[hi] = a[hi], a[p]
store = lo
for i in range(lo, hi):
if a[i] < a[hi]:
a[i], a[store] = a[store], a[i]
store += 1
a[store], a[hi] = a[hi], a[store]
if store == target:
return a[store]
if store < target:
lo = store + 1
else:
hi = store - 1function quickselect(a: number[], k: number): number {
const target = a.length - k;
let lo = 0, hi = a.length - 1;
const swap = (i: number, j: number) => ([a[i], a[j]] = [a[j], a[i]]);
while (true) {
swap(lo + Math.floor(Math.random() * (hi - lo + 1)), hi);
let store = lo;
for (let i = lo; i < hi; i++) if (a[i] < a[hi]) swap(i, store++);
swap(store, hi);
if (store === target) return a[store];
if (store < target) lo = store + 1; else hi = store - 1;
}
}Which approach?
| Approach | Time | Space | Best when |
|---|---|---|---|
| Sort | O(n log n) | O(1)–O(n) | Simplest; n small |
| Heap of size k | O(n log k) | O(k) | Streams, k much smaller than n |
| Bucket sort | O(n) | O(n) | Keys are bounded (frequencies) |
| Quickselect | O(n) expected | O(1) | One-shot, in-memory array |
- Kth Largest Element in an Arraymedium
- Kth Largest Element in a Streameasy
- Top K Frequent Elementsbucket sortmedium
- Top K Frequent Wordstie-break alphabeticallymedium
- K Closest Points to Originmax-heap of size kmedium
- Find K Closest Elementsbinary search a windowmedium
- Sort Characters By Frequencymedium
- Reorganize Stringmax-heap; alternate the top twomedium
- Task Schedulermedium
- Last Stone Weighteasy
- k largest ⇒ min-heap of size k (and vice versa).
- O(n log k) time, O(k) space; works on streams.
- Bounded keys (frequencies) ⇒ bucket sort in O(n).
- Quickselect: expected O(n), in place; randomise the pivot.