Top K Frequent Elements in Array - | | Practice | GeeksforGeeks

Given a non-empty array of integers, find the top k elements which have the highest frequency in the array. If two numbers have the same frequency then the larger number should be given preference. 
Note: Print the elements according to the frequency count (from highest to lowest) and if the frequency is equal then larger number will be given preference.
Example 1:
Input:
N = 6
nums = {1,1,1,2,2,3}
k = 2
Output: {1, 2}

Example 2:
Input:
N = 8
nums = {1,1,2,2,3,3,3,4}
k = 2
Output: {3, 2}
Explanation: Elements 1 and 2 have the
same frequency ie. 2. Therefore, in this
case, the answer includes the element 2
as 2 > 1.
User Task:
The task is to complete the function topK() that takes the array and integer k as input and returns a list of top k frequent elements.
Expected Time Complexity : O(NlogN)
Expected Auxilliary Space : O(N)
Constraints: 
1 <= N <= 105
1<=A[i]<=105
0
hrithikraina20011 week ago
 priority_queue<pair<int,int> >pq;
     map<int,int>mp;
     
     vector<int>ans;
     
     
     for(int i=0;i<nums.size();i++)
     {
         mp[nums[i]]++;
         
     }
     for(auto it:mp)
     {
         pq.push({it.second,it.first});
         
     }
     
     for(int i=0;i<k;i++)
     {
         ans.push_back(pq.top().second);
         pq.pop();
     }
     return ans;
0
akhilyadav00882 weeks ago
c++ solution with best time complexity
  priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> minh;       unordered_map<int,int> mp;       int n= nums.size();       for(int i=0;i<n;i++)       mp[nums[i]]++;       for(auto i=mp.begin();i!=mp.end();i++)       {           minh.push({i->second , i->first});           if(minh.size()>k)           minh.pop();       }       vector<int> res;       while(minh.size()>0)       {           res.push_back((minh.top()).second);           minh.pop();       }       reverse(res.begin(), res.end());       return res;
+1
geeky20092 weeks ago
vector<int> topK(vector<int>& nums, int k) {       // Code here       map<int,int>m;       vector<int>v;       for(int i=0;i<nums.size();i++){           m[nums[i]]++;       }      vector<pair<int,int>>v2;      for(auto x:m){          v2.push_back({x.second,x.first});      }      sort(v2.begin(),v2.end(),greater<pair<int,int>>());            for(int i=0;i<k;i++){          v.push_back(v2[i].second);      }   return v;      }
0
mitradiptamoy2 weeks ago
//C++ using unordered_map
vector<int> topK(vector<int>& nums, int k) {       // Code here       unordered_map<int,int>mp;       vector<int>ans;       vector<pair<int,int>>vec;       for(int i=0;i<nums.size();i++)       {           mp[nums[i]]=mp[nums[i]]+1;       }       for(auto it:mp)       {           vec.push_back({it.second,it.first});       }       sort(vec.begin(),vec.end(),greater<pair<int,int>>());       for(int i=0;i<k;i++)       {           ans.push_back(vec[i].second);       }       return ans;   }
+1
sagrikasoni2 weeks ago
class Solution {
    public int[] topK(int[] nums, int k) {
       HashMap<Integer, Integer> map = new HashMap<>();
       for(int val: nums)
       map.put(val, map.getOrDefault(val, 0)+1);
       
       PriorityQueue<Integer> pQueue= new PriorityQueue<>((a,b)->{
        
          if(map.get(a)==map.get(b))
              return a-b;
          return map.get(a) - map.get(b);
          });
       for(int n: map.keySet())
       {
           pQueue.add(n);
           if(pQueue.size()>k)
           pQueue.poll();
       }
       int [] ans = new int[k];
       
   for(int i = k - 1; i >= 0;i--) {
            ans[i] = pQueue.poll();
        }
        return ans;
    }
}
+1
siddharth1923co10682 weeks ago
tym 0.42 Brute force approach
/*firstly creating a hash map for storing freaquency of each element.
then placing this element along with frequecny in vector pair
applying sorting to the given array then in final step returning the first k most frequent element in the array.*/
 
 
       vector<int> topKFrequent(vector<int>& nums, int k) {       unordered_map<int,int>map;       vector<pair<int,int>>high;       vector<int>ans;       for(int i=0;i<nums.size();i++){           map[nums[i]]++;       }       for(auto it:map){           auto a=make_pair(it.second,it.first);           high.push_back(a);       }       //for (auto it=map.begin(); it!=map.end(); ++it)           sort(high.begin(),high.end(),greater<pair<int,int>>());       for(int i=0;i<k;i++){           ans.push_back(high[i].second);       }       return ans;   }
+2
aryany8712 weeks ago
//Time Complexity-O(nlogk) , Auxiliary Space-O(n) 
 
vector<int> topK(vector<int>& a, int k) {    unordered_map<int,int> m;              for(auto it : a){//-O(n)           m[it]++;       }              //min heap    priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;              for(auto it : m){//-O(nlogk)           pq.push({it.second,it.first});       //inserting freq first as it's sorted using first element by default                      if(pq.size()>k){               pq.pop();           }                  }              vector<int> v(k);       for(int i=k-1;i>=0;i--){//O(klogk)          auto it =pq.top();          v[i]=it.second;          pq.pop();       }              return v;          }
0
aryany871
This comment was deleted.
0
princechaudhary0073 weeks ago
timeComplexity=(NlogN)
//
static bool comp(pair<int,int>a,pair<int,int>b){       if(a.second==b.second) return a.first>b.first;       return a.second>b.second;   }   vector<int> topK(vector<int>& arr, int k) {       // Code here       unordered_map<int,int>mp;       int n=arr.size();       for(int i=0;i<n;i++){           mp[arr[i]]++;       }       vector<pair<int,int>>v;       for(auto x:mp){           v.push_back(x);       }       sort(v.begin(),v.end(),comp);       vector<int>ans;       for(int i=0;i<k;i++){            ans.push_back(v[i].first);       }          return ans;   }};
0
itachinamikaze2211 month ago
JAVA
class Solution {   public int[] topK(int[] nums, int k) {       HashMap<Integer, Integer> map = new HashMap<>();       for(int val: nums)       map.put(val, map.getOrDefault(val, 0)+1);              PriorityQueue<Integer> pQueue= new PriorityQueue<>((a,b)->{          int aValue=map.get(a);          int bValue=map.get(b);          if(aValue==bValue)              return a-b;          return aValue - bValue;          });       for(int n: map.keySet())       {           pQueue.add(n);           if(pQueue.size()>k)           pQueue.poll();       }       int []a = new int[k];       int i=k-1;       while(pQueue.isEmpty()==false)       {           int n=pQueue.poll();           a[i]=n;           i--;       }             return a;   }}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.