Advertisement
imashutosh51

Top k numbers in a stream

Aug 9th, 2022 (edited)
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.16 KB | None | 0 0
  1. /*
  2. T.C O(n*k) S.C O(K+1)
  3. Logic:
  4. we will create a top vector of k+1 length where 0 to k-1th index will store the top k most frequent numbers and
  5. in descending order of frequency and a map which will store the frequency of whole array.
  6. Traverse the whole array:
  7.   ->The last position of top vector is of no use so we will put the current element and increase it's frequency in map.
  8.   ->before current element,we had k most frequent elements at top from 0 to k-1th index,so now frequency of current element
  9.     is increase by 1 so there is only 2 possibility,either current element will be in top k most frequent or not.
  10.  
  11.   ->So we will find the first position of current element in top array because frequency incremented in only current element
  12.     so only current element can go it's left only so we will start swapping the elements from j to 0 on the basis of frequency
  13.     in decreasing order,this will surely adjust current element at it's orginal position as per frequency,even one iteration
  14.     is enough for one element adjustment so rest element is already at their position as per frequency,only current element
  15.     frequency is updated.
  16. */
  17.  
  18.  
  19. class Solution
  20. {
  21.   public:
  22.     vector<int> kTop(int arr[], int n, int k)
  23.     {
  24.         vector <int> top(k+1,0);
  25.         unordered_map<int,int> mp;
  26.         vector <int> ans;
  27.         for(int i=0;i<n;i++){
  28.             top[k]=arr[i];
  29.             mp[top[k]]++;
  30.             int j=0;
  31.             for(j=0;j<k;j++){   //we have not started swapping from k to 0 because there is possibility that
  32.                 if(top[j]==arr[i]) break;  //current element is already in top k element so get the first index of current element
  33.             }
  34.             while(j>0){
  35.                 if(mp[top[j]]>mp[top[j-1]]) swap(top[j],top[j-1]);
  36.                 if(mp[top[j]]==mp[top[j-1]] && top[j]<top[j-1]) swap(top[j],top[j-1]);//if frequency same,keeping numbers in decreasing order
  37.                 j--;
  38.             }
  39.            
  40.             for(int l=0;l<k && top[l]!=0;l++) ans.push_back(top[l]);//pushing first k elements in result array and breaking the loop if top size is less than k.
  41.         }
  42.         return ans;
  43.     }
  44. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement