MediumNo. 0347

Top K Frequent Elements — LeetCode 347 Python Solution

Topics
Array, Hash Table, Divide and Conquer, Bucket Sort, Counting, Quickselect, Sorting, Heap (Priority Queue)
On study lists
Blind 75 and NeetCode 150
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

PythonSolution
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

Time
O(n log k)
Space · auxiliary
O(k)

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

Related problems
No.ProblemDifficulty
0692Top K Frequent WordsMedium
0169Majority ElementEasy
0451Sort Characters By FrequencyMedium
0621Task SchedulerMedium
1054Distant BarcodesMedium
0229Majority Element IIMedium

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.

Free to download. Check it runs on your machine, then pick a plan.