MediumNo. 0347
Top K Frequent Elements — LeetCode 347 Python Solution
- Pattern
- Heap / Priority Queue
- 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
- 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
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
| No. | Problem | Difficulty |
|---|---|---|
| 0692 | Top K Frequent Words | Medium |
| 0169 | Majority Element | Easy |
| 0451 | Sort Characters By Frequency | Medium |
| 0621 | Task Scheduler | Medium |
| 1054 | Distant Barcodes | Medium |
| 0229 | Majority Element II | Medium |
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.