imashutosh51

Top K Frequent elements

Oct 18th, 2022 (edited)
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.57 KB | None | 0 0
  1. /*
  2. Logic1:
  3. use a map and store frequency of each element.make a min heap of k size.
  4. push elements from map to min heap where first element should be frequency
  5. and second element as elements that sorting happen on the basis of first element.
  6. while pushing compare top elememt of min heap with current element of map,if current
  7. element frequency is greater than top element,remove the top element and push current
  8. element else continue.
  9. finally all element of heap is the answer.
  10.  
  11. Logic2:
  12. 1.Count the frequency of each element using a Python dictionary.
  13. 2.Create a list of empty lists where index represent frequency and list is used because multiple elements can have same freq.
  14. 3.Insert each element into the list at its frequency index.
  15. 4.Traverse this list from highest index to lowest.
  16. 5.Collect elements until k most frequent elements are obtained.*/
  17.  
  18. from typing import List
  19. class Solution:
  20.     def topKFrequent(self, arr: List[int], k: int) -> List[int]:
  21.         freq_map = {}
  22.         _max = 0
  23.         ans = []
  24.  
  25.         # frequency map
  26.         for num in arr:
  27.             freq_map[num] = freq_map.get(num, 0) + 1
  28.             _max = max(_max, freq_map[num])
  29.  
  30.         # bucket array (list of lists)
  31.         freq = [[] for _ in range(_max + 1)]
  32.  
  33.         for num, count in freq_map.items():
  34.             freq[count].append(num)
  35.  
  36.         # traverse from highest frequency
  37.         for i in range(_max, 0, -1):
  38.             for num in freq[i]:
  39.                 ans.append(num)
  40.                 if len(ans) == k:
  41.                     return ans
  42.  
  43.         return ans
  44.  
  45.  
Advertisement
Add Comment
Please, Sign In to add comment