Top K Frequent Elements — LeetCode 347 Python Solution
MediumArrayHash TableDivide and ConquerBucket SortCountingQuickselectSortingHeap (Priority Queue)
- Problem
- #347
- Pattern
- Heap / Priority Queue
- Reading time
- 2 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n \log k) |
| Space | O(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.