DEV Community

WhereIsLijah
WhereIsLijah

Posted on

347. Top K Frequent Elements

Topic: Arrays & Hashing

Soln 1 (dictionary + lambda):

  1. Create an empty dictionary
  2. Iterate through the list "nums" with num:
  3. if the key [num] is not in the dictionary, then add to both the key [num] and the value [occurrence] 1 as the first occurence of that key [num]
  4. else it means the key [num] already exists and you need to increment the value [occurrence] in the dictionary
  5. Sort the dictionary items by their values in descending order, extract the keys of the top k items, and return.
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        freq_dict = {}

        for i in nums:
            if i not in freq_dict:
                freq_dict[i] = 1
            else:
                freq_dict[i] +=1

        return [item[0] for item in (sorted(freq_dict.items(), key=lambda item: item[1], reverse=True)[:k])]
Enter fullscreen mode Exit fullscreen mode

Soln 2 (dictionary + lambda):

  1. Create an empty dictionary
  2. iterate through the list "nums" using num:
  3. get the value of num, if it exists, increment by 1, else, assign a default value of 0
  4. Sort the dictionary items by their values in descending order using a lambda function
  5. Return a list of the first k keys from the sorted dictionary.
dic = {}
        for num in nums:
            dic[num] = dic.get(num, 0) + 1

        freq = dict(sorted(dic.items(), key=lambda x: x[1], reverse=True))
        return list(freq.keys())[:k]
Enter fullscreen mode Exit fullscreen mode

Notes:
A lambda is an anonymous function that can be used in place of a normal function. It can take arguments and is often used with higher-order functions.

Syntax: Lambda arguments: expression
e.g

cubed = lambda x: x**3
nums = [1, 2, 3]
cubed_nums = list(map(cubed, nums))
# Output: [1, 8, 27]
Enter fullscreen mode Exit fullscreen mode

Higher-order functions, e.g map, reduce, filter, zip, sorted

Top comments (0)