Data Structures19 sections · 729 units
Open in Course

Top K Frequent - Algorithm

Two-phase approach

Phase 1: Count frequencies using a hash map. Phase 2: Find the kk elements with highest frequency using a heap.

For phase 2, you can either:

  • Use a min-heap of size kk (keep kk most frequent)
  • Use a max-heap of all elements and extract kk times

The min-heap approach is O(nlogk)O(n \log k), better when kk is small. Time: O(nlogk)O(n \log k). Space: O(n)O(n).