allizwell.jobsdoor360.in

Top K Frequent Elements

Data Structures and Algorithms / Heaps / Top K Frequent Elements

Top K Frequent Elements in an Array

The Top K Frequent Elements problem asks us to find the K elements that occur most frequently in an array. Instead of sorting the complete array, we can use a Hash Map to count frequencies and a Heap to efficiently select the most frequent elements. This is an important problem that combines Hashing and Heaps.

1. What Is the Top K Frequent Elements Problem?

Given an array of integers and a number K, we need to find the K elements that appear the greatest number of times.

Example:

Array = [1, 1, 1, 2, 2, 3]

K = 2

The number 1 appears 3 times, 2 appears 2 times, and 3 appears 1 time.

Answer: [1, 2]

We return the two elements with the highest frequencies. Their order in the returned answer is not important unless the problem specifically requires a particular order.

2. Understanding Frequency

Frequency means the number of times an element appears in an array.

Consider this array:

[4, 4, 4, 2, 2, 7, 7, 7, 7, 9]

Its frequency table is:

Element Frequency
4 3
2 2
7 4
9 1

If K = 2, the two most frequent elements are 7 and 4.

Answer = [7, 4]

3. Approach 1: Hash Map and Sorting

The simplest approach is to count the frequency of every element using a Hash Map and then sort the elements according to their frequencies.

Steps

  1. Create a Hash Map to store each element and its frequency.
  2. Traverse the array and increase the frequency of each element.
  3. Move the elements and their frequencies into a vector.
  4. Sort the vector in descending order of frequency.
  5. Return the first K elements.

C++ Program

#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;

vector<int> topKFrequent(vector<int>& arr, int k) {

    unordered_map<int, int> freq;

    // Count frequencies
    for (int num : arr) {
        freq[num]++;
    }

    // Store element and frequency
    vector<pair<int, int>> elements;

    for (auto entry : freq) {
        elements.push_back({entry.first, entry.second});
    }

    // Sort by frequency in descending order
    sort(elements.begin(), elements.end(),
         [](pair<int, int> a, pair<int, int> b) {
             return a.second > b.second;
         });

    vector<int> result;

    for (int i = 0; i < k; i++) {
        result.push_back(elements[i].first);
    }

    return result;
}

int main() {

    vector<int> arr = {1, 1, 1, 2, 2, 3};

    int k = 2;

    vector<int> result = topKFrequent(arr, k);

    cout << "Top K Frequent Elements: ";

    for (int num : result) {
        cout << num << " ";
    }

    return 0;
}

Output

Top K Frequent Elements: 1 2

Explanation

  • The Hash Map counts the occurrences of every element.
  • The frequency of 1 is 3.
  • The frequency of 2 is 2.
  • The frequency of 3 is 1.
  • The elements are sorted by frequency.
  • The first K elements are returned.

Complexity Analysis

  • Frequency Counting: O(N) average time.
  • Sorting: O(M log M) time.
  • Overall: O(N + M log M).
  • Space: O(M), where M is the number of distinct elements.
Limitation: Sorting all distinct elements may take unnecessary time when K is small. A Heap can help us select only the K most frequent elements.

4. Approach 2: Hash Map and Min Heap

A Min Heap of size K is an efficient way to find the K most frequent elements.

First, we count the frequency of every element using a Hash Map. Then we insert element-frequency pairs into a Min Heap.

The Min Heap keeps the element with the smallest frequency at its root. If the Heap contains more than K elements, we remove the root.

Why Do We Use a Min Heap?

We want to keep only the K elements with the highest frequencies. Therefore, the smallest frequency among the selected elements should be at the root.

Whenever a new element is inserted and the Heap size becomes greater than K, we remove the element with the smallest frequency.

After processing all distinct elements, the Heap contains the K most frequent elements.

Algorithm

  1. Create an unordered_map to count element frequencies.
  2. Create a Min Heap of element-frequency pairs.
  3. Insert each distinct element with its frequency.
  4. If Heap size becomes greater than K, remove the root.
  5. Extract all remaining elements from the Heap.
  6. Return the extracted elements.

C++ Program

#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
using namespace std;

vector<int> topKFrequent(vector<int>& arr, int k) {

    unordered_map<int, int> freq;

    // Count frequencies
    for (int num : arr) {
        freq[num]++;
    }

    // Min Heap based on frequency
    priority_queue<
        pair<int, int>,
        vector<pair<int, int>>,
        greater<pair<int, int>>
    > pq;

    // Maintain only K elements
    for (auto entry : freq) {

        pq.push({entry.second, entry.first});

        if (pq.size() > k) {
            pq.pop();
        }
    }

    vector<int> result;

    while (!pq.empty()) {

        result.push_back(pq.top().second);

        pq.pop();
    }

    return result;
}

int main() {

    vector<int> arr = {1, 1, 1, 2, 2, 3};

    int k = 2;

    vector<int> result = topKFrequent(arr, k);

    cout << "Top K Frequent Elements: ";

    for (int num : result) {
        cout << num << " ";
    }

    return 0;
}

Output

Top K Frequent Elements: 2 1

The order may differ because the problem does not require a particular order. Both 1 and 2 are the correct two most frequent elements.

5. Understanding the Min Heap with an Example

Consider the following array:

[1, 1, 1, 2, 2, 3]

K = 2

First, create the frequency table:

Element Frequency
1 3
2 2
3 1

We now insert the element-frequency pairs into a Min Heap. Each pair is stored as:

{frequency, element}

Operation Heap Contents Action
Insert {3, 1} {3, 1} Insert first element
Insert {2, 2} {2, 2}, {3, 1} Insert second element
Insert {1, 3} {1, 3}, {3, 1}, {2, 2} Heap size becomes 3
Remove root {2, 2}, {3, 1} Remove frequency 1

Since K = 2, the Heap keeps only two elements. The element with frequency 1 is removed.

Final Elements = 1 and 2

6. Time and Space Complexity

Let:

  • N = Total number of elements in the array.
  • M = Number of distinct elements.
  • K = Number of most frequent elements required.
Operation Time Complexity
Build frequency map O(N) average
Insert into Min Heap O(log K) per insertion when Heap is maintained at size K
Process M distinct elements O(M log K)
Extract K elements O(K log K)

Overall Time Complexity:

O(N + M log K)

Since K cannot exceed M, the extraction cost is covered by the Heap processing bound.

Space Complexity:

O(M + K) = O(M)

The Hash Map stores M distinct elements, and the Heap stores at most K elements.

7. Handling Equal Frequencies

Sometimes two or more elements have the same frequency. In such cases, the problem statement may allow any valid answer or may specify a tie-breaking rule.

Example:

Array = [1, 1, 2, 2, 3, 3, 4]

K = 2

Elements 1, 2, and 3 each appear twice.

Any two of these three elements can be a valid answer if the problem does not specify how ties should be handled.

Important: The C++ pair-based Min Heap compares the first value first. If frequencies are equal, it compares the second value. This gives a deterministic tie-breaking order for integer elements. If a problem requires a different tie-breaking rule, use a custom comparator.

8. Approach 3: Bucket Sort

Another way to solve the Top K Frequent Elements problem is Bucket Sort.

The maximum possible frequency of an element is N because an element can appear at most N times in an array of size N. We can use this fact to create frequency buckets.

Steps

  1. Count the frequency of every element using a Hash Map.
  2. Create buckets indexed by frequency.
  3. Place each element into the bucket matching its frequency.
  4. Traverse the buckets from highest frequency to lowest.
  5. Collect elements until K elements have been selected.

C++ Program

#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

vector<int> topKFrequent(vector<int>& arr, int k) {

    unordered_map<int, int> freq;

    // Count frequencies
    for (int num : arr) {
        freq[num]++;
    }

    // Create frequency buckets
    vector<vector<int>> buckets(arr.size() + 1);

    for (auto entry : freq) {

        int element = entry.first;
        int count = entry.second;

        buckets[count].push_back(element);
    }

    vector<int> result;

    // Traverse from highest frequency
    for (int i = arr.size(); i >= 1; i--) {

        for (int num : buckets[i]) {

            result.push_back(num);

            if (result.size() == k) {
                return result;
            }
        }
    }

    return result;
}

int main() {

    vector<int> arr = {1, 1, 1, 2, 2, 3};

    int k = 2;

    vector<int> result = topKFrequent(arr, k);

    cout << "Top K Frequent Elements: ";

    for (int num : result) {
        cout << num << " ";
    }

    return 0;
}

Output

Top K Frequent Elements: 1 2

Complexity Analysis

  • Frequency Counting: O(N) average.
  • Bucket Creation: O(N + M).
  • Bucket Traversal: O(N + M) in the worst case.
  • Overall Time: O(N) average.
  • Space: O(N + M), which is O(N) because M cannot exceed N.

9. Comparison of Different Approaches

Approach Time Complexity Extra Space
Hash Map + Sorting O(N + M log M) O(M)
Hash Map + Min Heap O(N + M log K) O(M + K)
Bucket Sort O(N) average O(N)

The Heap approach is useful when K is small compared with the number of distinct elements. Bucket Sort can be efficient when we want to avoid comparison-based sorting.

10. Common Mistakes

  • Counting the total number of array elements instead of counting the frequency of each distinct element.
  • Forgetting that the Heap should contain only K elements in the Min Heap approach.
  • Using the element value instead of its frequency to determine priority.
  • Confusing the K most frequent elements with the K largest numerical elements.
  • Assuming the returned elements must always be sorted by frequency.
  • Ignoring equal-frequency cases when a problem specifies a tie-breaking rule.
  • Accessing an invalid result when K is greater than the number of distinct elements.

11. Important Interview Questions

Q1. What is the Top K Frequent Elements problem?

It asks us to find the K distinct elements that occur most frequently in an array.

Q2. Which data structure is used to count frequencies?

A Hash Map or unordered_map is commonly used.

Q3. Which Heap is used for this problem?

A Min Heap of size K is commonly used to keep the K elements with the highest frequencies.

Q4. Why do we remove the root when Heap size exceeds K?

The root has the smallest frequency among the elements currently stored in the Min Heap. Removing it ensures that only the K most frequent elements remain.

Q5. What is the time complexity of the Heap approach?

O(N + M log K), where N is the array size and M is the number of distinct elements.

Q6. Can this problem be solved without a Heap?

Yes. We can use sorting or Bucket Sort.

Q7. What happens when two elements have the same frequency?

The answer depends on the problem statement. If no tie-breaking rule is specified, any valid selection may be accepted.

Q8. What is the difference between Kth Largest and Top K Frequent?

Kth Largest selects elements according to their numerical values. Top K Frequent selects elements according to how many times they occur.

12. Practice Problems

  1. Find the top 2 frequent elements in an array.
  2. Find the top 3 frequent elements using a Min Heap.
  3. Find the most frequent element in an array.
  4. Find the K most frequent numbers when negative values are also present.
  5. Solve the Top K Frequent Elements problem using sorting.
  6. Solve the same problem using a Min Heap.
  7. Solve the same problem using Bucket Sort.
  8. Handle multiple elements having the same frequency.
  9. Find the K most frequent words using a Hash Map and Heap.
  10. Compare the performance of Heap and Bucket Sort approaches.

13. Summary

The Top K Frequent Elements problem combines Hashing and Heaps. We first count the frequency of each element and then select the K elements with the highest frequencies.

  • A Hash Map stores the frequency of each distinct element.
  • A Min Heap of size K keeps the K most frequent elements.
  • The Heap approach takes O(N + M log K) average time.
  • Bucket Sort can solve the problem in O(N) average time.
  • Equal frequencies may require a tie-breaking rule.
  • Frequency and numerical value are two different concepts.
Key Takeaway: First use a Hash Map to count how frequently each element appears. Then use a Min Heap of size K to keep the K elements with the highest frequencies. This is a useful combination of two important DSA concepts: Hashing and Heaps.
Scroll to Top