
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
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 −
Example
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 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 ob1 = Solution() print(ob1.topKFrequent([1,1,1,1,2,2,3,3,3], 2))
Input
[1,1,1,1,2,2,3,3,3] 2
Output
[1, 3]
- Related Articles
- Find top K frequent elements from a list of tuples in Python
- Top K Frequent Words in C++
- Count Frequency of Highest Frequent Elements in Python
- Find the k most frequent words from data set in Python
- Write a program in C++ to find the top K frequent element in an array of integers
- Python – K middle elements
- How to find the k-th and the top "k" elements of a tensor in PyTorch?
- Python – Reform K digit elements
- Program to find k where k elements have value at least k in Python
- Delete elements with frequency atmost K in Python
- Extract tuples having K digit elements in Python
- Python – Remove Elements in K distance with N
- Python – Next N elements from K value
- Python – Random insertion of elements K times
- Maximum and Minimum K elements in Tuple using Python

Advertisements