Skip to content
Preptima
mediumCodingConceptMidSenior

Return the k most frequent elements from a large stream of values. Why not just sort by frequency?

4 min readUpdated 2026-08-15

Answer

Short answer

Count occurrences, then push counts through a min-heap capped at size k, evicting the smallest whenever the heap overflows. That is O(n log k) rather than the O(n log n) of a full sort, it needs only k items resident at once, and it works on a stream you cannot re-read.

Was this answer helpful?

Likely follow-ups

  • The stream has a billion distinct keys. Where does your solution break, and what replaces it?
  • Counts are bounded by n. Can you get to O(n) without a heap at all?
  • Maintain the running median of the same stream instead. What structure now?
  • Your comparator subtracts two counts. What is wrong with that?

Related questions

Further reading