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

Example

Let us see the following implementation to get better understanding −

class Solution(object):
   def topKFrequent(self, nums, k):
      """
      :type nums: List[int]
      :type k: int
      :rtype: List[int]
      """
      number_frequency = {}
      frequency_list ={}
      for i in nums:
         if i not in number_frequency:
            number_frequency[i] = 1
         else:
            number_frequency[i] += 1
      for key,value in number_frequency.items():
         if value not in frequency_list:
            frequency_list[value] = [key]
         else:
            frequency_list[value].append(key)
      result = []
      for i in range(len(nums),0,-1):
      if i in frequency_list:
         result.extend(frequency_list[i])
      if len(result) >=k:
         break
   return result

Input

[1,1,1,1,2,2,3,3,3]
2

Output

[1,3]
raja
Published on 05-Feb-2020 10:50:30
Advertisements