Here's the solution with a min-heap of size :
function topKFrequent(nums, k)
// Phase 1: Count frequencies
freq := empty hash map
for each num in nums
freq[num] := freq[num] + 1
// Phase 2: Find top k by frequency
heap := empty min-heap of (frequency, element) pairs
for each (element, count) in freq
if size of heap < k
insert (count, element) into heap
else if count > frequency at heap root
extract min from heap
insert (count, element) into heap
return all elements from heap
Time: . Space: .