LeetCode 347 Top K Frequent Elements - Why Naive Fails

The trap

Count frequencies with a hash map, then sort all unique elements by their counts. Take the first k.

With nums = [1, 1, 1, 2, 2, 3] and k = 2, you get counts {1: 3, 2: 2, 3: 1}. Sort by value descending: [(1, 3), (2, 2), (3, 1)]. Take top 22: [1, 2].

Sorting is O(mlogm)O(m \log m) where mm is the number of unique elements. In the worst case, m=nm = n, so this becomes O(nlogn)O(n \log n).

Can you do better than O(nlogn)O(n \log n)?