Top K Frequent Elements in Python

Suppose we have a non-empty array of integer numbers. we have to return the kth most frequent elements. So if the elements are [1,1,1,1,2,2,3,3,3] and k = 2, then the result will be

Formally the function should −

  • Return true if there exists i, j, k
  • such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.

To solve this, we will follow these steps −

  • num_freq = an empty map, freq_list := an empty map
  • for each element i in nums
    • if i is not in num_freq, then num_freq[i] := 1, otherwise increase num_freq[i] by 1
  • for each key-value pair in num_freq map
    • if value is not present in freq_list, then freq_list[value] := a list with [key], otherwise insert key into freq_list[value] array
  • res := empty list
  • for i := length of numbers down to 0
    • if i in freq_list, then add elements of freq_list[i] into res
    • if length of res >= k, then break
  • return result

Let us see the following implementation to get better understanding −


 Live Demo

class Solution(object):
   def topKFrequent(self, nums, k):
      number_frequency = {}
      frequency_list ={}
      for i in nums:
         if i not in number_frequency:
            number_frequency[i] = 1
            number_frequency[i] += 1
      for key,value in number_frequency.items():
         if value not in frequency_list:
            frequency_list[value] = [key]
      result = []
      for i in range(len(nums),0,-1):
         if i in frequency_list:
         if len(result) >=k:
      return result
ob1 = Solution()
print(ob1.topKFrequent([1,1,1,1,2,2,3,3,3], 2))




[1, 3]