Leetcode Problem 347: Top K Frequent Elements

Problem description:

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Python solution Link to heading


# leetcode_347.py


class Solution:
    def topKFrequent(self, nums: list[int], k: int) -> list[int]:
        n = len(nums)
        occurrences = {}
        for i in range(0, n):
            occurrences[nums[i]] = occurrences.get(nums[i], 0) + 1

        l = sorted(occurrences.items(), key=lambda item: item[1], reverse=True)[:k]
        return [num[0] for num in l]

Python statistics Link to heading
Runtime: 178 ms - beats 23.20 % of python3 submissions.
Memory Usage: 18.6 MB -- beats 67.53 % of python3 submissions.
Complexity analysis Link to heading
  • Time: $ O(n + n + n) = O(3n) = O(n)$, where every $ n $ coincides with the for loops iteration.

  • Space: $ O(n + n + n) = O(3n) = O(n) $ since we create a dictionary and two lists the size of the input array.



Share on:
LinkedIn