0
0
DSA Typescriptprogramming~3 mins

Why Top K Frequent Elements Using Heap in DSA Typescript?

Choose your learning style9 modes available
The Big Idea

What if you could find the most popular things in a huge list without sorting everything?

The Scenario

Imagine you have a huge list of words from a book, and you want to find the top 3 most common words. Doing this by counting each word manually and sorting the entire list is like counting every grain of sand on a beach by hand.

The Problem

Manually counting frequencies and sorting all words takes a lot of time and effort, especially if the list is very large. It's easy to make mistakes, and sorting everything wastes time when you only want the top few.

The Solution

Using a heap helps you keep track of the top frequent words efficiently. Instead of sorting everything, the heap keeps only the most frequent words at the top, so you quickly find the top K without extra work.

Before vs After
Before
const counts = new Map();
for (const word of words) {
  counts.set(word, (counts.get(word) || 0) + 1);
}
const sorted = [...counts.entries()].sort((a, b) => b[1] - a[1]);
const topK = sorted.slice(0, k).map(entry => entry[0]);
After
const counts = new Map();
for (const word of words) {
  counts.set(word, (counts.get(word) || 0) + 1);
}
const minHeap = new MinHeap((a, b) => a.freq - b.freq);
for (const [word, freq] of counts.entries()) {
  minHeap.insert({word, freq});
  if (minHeap.size() > k) minHeap.extractMin();
}
const topK = minHeap.toArray().map(item => item.word);
What It Enables

This method lets you quickly find the most frequent items in huge data sets without wasting time sorting everything.

Real Life Example

Social media platforms use this to show trending hashtags by quickly finding the top used tags from millions of posts.

Key Takeaways

Manual counting and sorting is slow and error-prone for large data.

Heap keeps track of top K frequent elements efficiently.

Using a heap saves time and memory when only top results matter.