Top K Frequent Elements — LeetCode 347 Python Solution

MediumArrayHash TableDivide and ConquerBucket SortCountingQuickselectSortingHeap (Priority Queue)
Problem
#347
Reading time
2 min

The problem

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

Python
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        cnt = Counter(nums)
        return [x for x, _ in cnt.most_common(k)]

Complexity

MeasureComplexity
TimeO(n \log k)
SpaceO(k) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 347. Top K Frequent Elements is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

On study lists

This problem is on Blind 75 and NeetCode 150.

Frequently asked questions

How hard is LeetCode 347. Top K Frequent Elements?
LeetCode 347. Top K Frequent Elements is rated Medium on LeetCode.
What is the time complexity of LeetCode 347. Top K Frequent Elements?
The Python solution on this page runs in O(n \log k).
What is the space complexity of LeetCode 347. Top K Frequent Elements?
The Python solution on this page uses O(k) auxiliary space.
What topics does LeetCode 347. Top K Frequent Elements cover?
LeetCode 347. Top K Frequent Elements is tagged Array, Hash Table, Divide and Conquer, Bucket Sort, Counting, Quickselect, Sorting and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview