Top K Frequent Elements
Problem Statement
Given an array of integers, return the k most frequent elements.
Example: nums = [1,1,1,2,2,3], k=2 → Output: [1,2]
Approach 1: Hash Map + Sorting
Explanation: Count frequencies and sort by frequency.
Time Complexity: O(n log n)
Space Complexity: O(n)
freq = hashmap()
for num in nums:
freq[num] += 1
sort freq by values descending
return first k elements
Approach 2: Min Heap (Optimal)
Explanation: Maintain min-heap of size k for
frequencies.
Time Complexity: O(n log k)
Space Complexity: O(k)
freq = hashmap()
for num in nums:
freq[num] += 1
create min-heap
for num, count in freq:
push (count,num)
if heap size > k:
pop min
return all elements in heap