AlgoMaster Logo

Top K Frequent Elements

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Sorting

Intuition:

The most straightforward way to find the top k frequent elements is to count the frequency of each element using a hashmap, then sort the elements based on their frequency in descending order, and finally pick the first k elements from this sorted list.

Steps:

  1. Create a hashmap to count the frequency of each element.
  2. Transform hashmap entries into a list of pairs and sort it based on frequency.
  3. Extract the first k elements from the sorted list.

Code:

2. Priority Queue

Intuition:

Instead of sorting all elements, we can use a Min-Heap (Priority Queue) to keep track of the top k elements. As we iterate through the hashmap, we maintain the size of the heap to be at most k by removing the smallest element whenever the size exceeds k.

Steps:

  1. Use a hashmap to count the frequency of each element.
  2. Use a priority queue to keep track of the top k elements.
  3. Iterate through the map and push each entry into the Min-Heap, evicting the smallest when the heap exceeds size k.

Code:

3. Bucket Sort

Intuition:

We can utilize a bucket sort technique since the maximum frequency of any element can't exceed the number of elements. We'll create an array of lists where each index corresponds to a frequency, then we'll fill each list with the numbers that have the respective frequency.

Steps:

  1. Build the frequency map.
  2. Create buckets where index corresponds to frequency, and append elements to respective buckets.
  3. Iterate from the end of the bucket array to pick the top k frequent elements.

Code: