AlgoMaster Logo

Top K Frequent Words

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Frequency Map with Sorting

Intuition:

The main idea is to count the frequency of each word and then sort them by frequency. Since we need the top k frequent words, we can sort the entries and select the first k elements. As words with identical frequencies should be in alphabetical order, we ensure that in our sort function.

Steps:

  1. Use a hashmap to count the frequency of each word.
  2. Convert the hashmap into a list of entries (word and frequency pairs).
  3. Sort the list with a custom comparator:
    • First, by decreasing frequency.
    • Second, lexicographically in case of a tie in frequency.
  4. Extract the first k elements from the sorted list.

Code:

2. Min-Heap

Intuition:

A min-heap can efficiently help maintain the k most frequent elements, especially when we need to sort by frequency primarily. The idea is to always maintain k elements in the heap and eject elements when the heap grows beyond k, ensuring that the heap contains the most frequent words.

Steps:

  1. Count the frequency of each word using a hashmap.
  2. Use a PriorityQueue (min-heap) to maintain the k highest frequency words.
    • When adding new elements to the heap of size more than k, remove the smallest frequency word.
    • Use a custom comparator to sort by frequency and lexicographical order for words with the same frequency.
  3. Extract elements from the heap to form the result list.

Code: