Skip to main content

Top K Frequent Elements

Question

Given an unsorted array of numbers, find the K most frequent elements in the array.

Example 1
Input: [1,1,1,2,2,3]
k = 2

Output: [1,2]

Solution

all//Top K Frequent Elements.py


# Solution
class Solution:
def topKFrequent(self, nums, k):
# create a dictionary to store the frequency of each number
freq_dict = {}
for num in nums:
if num in freq_dict:
freq_dict[num] += 1
else:
freq_dict[num] = 1

# create a list of tuples (number, frequency)
freq_list = []
for num, freq in freq_dict.items():
freq_list.append((num, freq))

# sort the list in descending order
freq_list.sort(key=lambda x: x[1], reverse=True)

# return the top k elements
return [x[0] for x in freq_list[:k]]