Top K Frequent Elements: Why a Min-Heap of Size k Beats Sorting



Top K Frequent Elements is a classic coding interview question, and sorting every count costs O(n log n) when a min-heap capped at k does it in O(n log k). Here is the pattern, and the one case where bucket sort wins.

▸ Count every value with a hash map first, that part is always O(n)
▸ Keep a min-heap of size k for O(n log k) time and O(k) extra space
▸ Why a min-heap: the root is the weakest candidate, so it is the one to evict
▸ In C#, PriorityQueue (.NET 6+) is a min-heap by default, priority = frequency
▸ When k gets close to the number of distinct values, bucket sort by frequency gives O(n)

Subscribe for one interview problem broken down every week.

🌐 Website:
ⓕ Fan Page:
ⓕ FB:
📩 Business inquiries: duylinh191@gmail.com

#Shorts #TopKFrequentElements #MinHeap #CodingInterview #LeetCode #DataStructures #Algorithms #PriorityQueue #BigO #CSharp #DotNet #InterviewPrep

source

Leave a Reply

Your email address will not be published. Required fields are marked *

You might like

© 2026 Cantinho do Vídeo - WordPress Video Theme by WPEnjoy