1. Frequency Map + Bounded Size-K Min-Heap
Count frequencies in a hash map, then stream (freq, num) pairs through a Min-Heap capped at capacity k in O(n log k) time.
Building frequency map is O(n); pushing up to n unique keys through a size-k heap takes O(n log k).
Frequency map stores up to n keys plus O(k) heap space.
How It Works
Bounded Priority Selection Over Frequencies
After counting occurrences per distinct value in O(n), keeping only the top k pairs is identical to Kth Largest Element:
- Build
counts[val]acrossnums. - Push each
(freq, val)into a Min-Heap ordered byfreq. - Whenever
heap.size > k, pop the smallest frequency entry. - Collect all remaining keys in the heap (
O(n log k), which stays near-linear whenk << n).
Step-by-Step Dry Run
[1, 1, 1, 2, 2, 3] yields frequency pairs (3, 1), (2, 2), (1, 3).
counts = {1: 3, 2: 2, 3: 1}- +Beats O(n log n) sorting whenever k is small
- +Clean priority-queue pattern
- -Slightly slower than O(n) Bucket Sort when k approaches n
Reference Implementation
Complete implementation for Frequency Map + Bounded Size-K Min-Heap in Python, JavaScript, Java, C++, and C.
import heapqfrom collections import Counterdef top_k_frequent_heap(nums: list[int], k: int) -> list[int]:counts = Counter(nums)min_heap: list[tuple[int, int]] = []for num, freq in counts.items():heapq.heappush(min_heap, (freq, num))if len(min_heap) > k:heapq.heappop(min_heap)return [num for _, num in min_heap]
function topKFrequentHeap(nums, k) {
const counts = new Map();
for (const n of nums) counts.set(n, (counts.get(n) || 0) + 1);
const heap = [];
const push = (item) => {
heap.push(item);
let i = heap.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (heap[p][0] <= heap[i][0]) break;
[heap[p], heap[i]] = [heap[i], heap[p]];
i = p;
}
};
const pop = () => {
const top = heap[0];
const last = heap.pop();
if (heap.length > 0) {
heap[0] = last;
let i = 0;
while (true) {
let s = i, l = 2 * i + 1, r = 2 * i + 2;
if (l < heap.length && heap[l][0] < heap[s][0]) s = l;
if (r < heap.length && heap[r][0] < heap[s][0]) s = r;
if (s === i) break;
[heap[i], heap[s]] = [heap[s], heap[i]];
i = s;
}
}
return top;
};
for (const [num, freq] of counts.entries()) {
push([freq, num]);
if (heap.length > k) pop();
}
return heap.map(([, num]) => num);
}import java.util.*;
public class Solution {
public static int[] topKFrequentHeap(int[] nums, int k) {
Map<Integer, Integer> count = new HashMap<>();
for (int n : nums) count.put(n, count.getOrDefault(n, 0) + 1);
PriorityQueue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
for (Map.Entry<Integer, Integer> e : count.entrySet()) {
minHeap.offer(new int[]{e.getKey(), e.getValue()});
if (minHeap.size() > k) minHeap.poll();
}
int[] res = new int[k];
for (int i = 0; i < k; i++) res[i] = minHeap.poll()[0];
return res;
}
}#include <vector>
#include <unordered_map>
#include <queue>
#include <utility>
std::vector<int> topKFrequentHeap(const std::vector<int>& nums, int k) {
std::unordered_map<int, int> count;
for (int n : nums) count[n]++;
using P = std::pair<int, int>; // (freq, val)
std::priority_queue<P, std::vector<P>, std::greater<P>> minHeap;
for (const auto& kv : count) {
minHeap.push({kv.second, kv.first});
if (static_cast<int>(minHeap.size()) > k) minHeap.pop();
}
std::vector<int> res;
while (!minHeap.empty()) {
res.push_back(minHeap.top().second);
minHeap.pop();
}
return res;
}#include <stdlib.h>
typedef struct { int val; int count; } FreqItem;
static int cmpMinFreq(const void* a, const void* b) {
return ((const FreqItem*)b)->count - ((const FreqItem*)a)->count;
}
int* topKFrequentSort(const int* nums, int n, int k, int* returnSize) {
int range = 20001, offset = 10000;
int* counts = (int*)calloc(range, sizeof(int));
for (int i = 0; i < n; i++) counts[nums[i] + offset]++;
FreqItem* items = (FreqItem*)malloc(n * sizeof(FreqItem));
int u = 0;
for (int v = 0; v < range; v++) {
if (counts[v] > 0) {
items[u++] = (FreqItem){v - offset, counts[v]};
}
}
qsort(items, u, sizeof(FreqItem), cmpMinFreq);
int* res = (int*)malloc(k * sizeof(int));
for (int i = 0; i < k; i++) res[i] = items[i].val;
*returnSize = k;
free(counts);
free(items);
return res;
}