Question: https://leetcode.com/problems/top-k-frequent-elements/description/

I tried to solve it with a simplistic approach.

First, I stored the occurrences of each element in the array.

Then, I sorted the occurrences dictionary in descending order of the values it had. (I learnt how to do that using lambda function inside the sorted method.)

Next, based on how many top elements were needed I added them to the result list.

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        occ = {}
        res = []
        for i in nums:
            if i not in occ:
                occ[i] = 1
            elif i in occ:
                occ[i] += 1
        # Sorting the dictionary by its values in descending order
        sorted_dict_descending = dict(sorted(occ.items(), key=lambda item: item[1], reverse=True))
        list_dict = list(sorted_dict_descending.keys())
        for i in range(k):
            res.append(list_dict[i])
        return res

I was in a hurry because of some work so I did not solve to optimize it today.