68 / 75
M

Top K Frequent Elements

#68
arrayhash-tableheap+2

Count frequencies with HashMap, use min-heap of size k to track top k elements.

Example:

Input:nums=[1,1,1,2,2,3], k=2
Output:[1,2] (most frequent elements)

Common Mistakes:

  • Using max-heap and keeping all elements (inefficient O(n log n))
  • Not comparing by frequency in heap comparator
  • Sorting entire array when heap suffices
  • Not handling ties in frequency correctly

Notes:

Time O(n log k) with heap. Space O(n). Can optimize to O(n) with bucket sort or quickselect. Follow-up asks for better than O(n log n).

68/75
Top K Frequent Elements