(128). 32.7. HASHING TOP K MOST FREQUENT ELEMENT. - anishsingh90/Data_Structure_And_Algorithm_In_Cpp_github.io GitHub Wiki

#include <bits/stdc++.h> using namespace std;

int main() { int n; cout << "Enter the size of array: "; cin >> n;

int k;
cout << "Enter the K: ";
cin >> k;

vector<int> a(n); 

for (int i = 0; i < n; i++) {
    cin >> a[i];
}

map<int, int> freq;

for (int i = 0; i < n; i++) { 
    int presentSize = freq.size();
    if (freq[a[i]] == 0 && presentSize == k) {
        break;
    }
    freq[a[i]]++;
}

vector<pair<int, int>> ans; 

for (auto it = freq.begin(); it != freq.end(); it++) {
    if (it->second != 0) { 
        ans.push_back(make_pair(it->second, it->first)); 
    }
}

sort(ans.begin(), ans.end(), greater<pair<int, int>>()); 

vector<pair<int, int>>::iterator it1;

for (it1 = ans.begin(); it1 != ans.end(); it1++) {
    cout << it1->second << " " << it1->first << endl; 
}

return 0;

}

/* OUTPUT: Enter the size of array: 6 Enter the K: 2 1 2 2 2 3 1 2 3 1 1 */

⚠️ **GitHub.com Fallback** ⚠️