Skip to content

Top K Frequent Elements

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

InputkOutput
[1,1,1,2,2,3]2[1,2]
[1]1[1]
  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • k is in the range [1, the number of unique elements in the array]
  • The answer is guaranteed to be unique
ApproachTimeSpaceBest When
Max HeapO(n log k)O(n)k << n, memory matters
Bucket SortO(n)O(n)Best asymptotic, when n is large
  • Pick Max Heap for interviews — it is the expected answer and generalises to streaming data.
  • Pick Bucket Sort when you want the asymptotically optimal O(n) solution and can mention it as the follow-up.
Recommended
Max Heap
O(n log k) time · O(n) space
Interview Favourite
Bucket Sort
O(n) time · O(n) space
★ Recommended

Count element frequencies with a hash map, then push all (freq, num) pairs into a max-heap. Pop k times to get the top-k most frequent elements.

⏱ Time O(n log k) n insertions into a heap of size ≤ n 💾 Space O(n) Freq map + heap store all unique elements

Input: nums = [1,1,1,2,2,3], k = 2

StepState
Build freq map{1:3, 2:2, 3:1}
Max-heap (by freq)[(3,1), (2,2), (1,3)]
Pop 1element 1 (freq 3)
Pop 2element 2 (freq 2)
Return[1, 2]

Animated walkthrough

How the max heap extracts the top-k most frequent elements

Use Next or Autoplay to watch frequency counting and then heap extraction.

Step 1 of 3
Waiting to begin...
Array state
Memory / lookup state

function topKFrequent(nums, k):
freq = count all nums
return k largest by frequency from freq
top_k_frequent_max_heap.py
from typing import List
from collections import Counter
import heapq
def topKFrequent(nums: List[int], k: int) -> List[int]:
freq = Counter(nums)
# heapq.nlargest uses a heap internally — O(n log k)
return heapq.nlargest(k, freq.keys(), key=lambda x: freq[x])
print(topKFrequent([1, 1, 1, 2, 2, 3], 2)) # [1, 2]
print(topKFrequent([1], 1)) # [1]
🎯 Interview Favourite

Since frequency is bounded by n, create n+1 buckets indexed by frequency. bucket[i] holds all numbers that appear exactly i times. Fill from the freq map, then iterate buckets from high to low, collecting elements until k are found. This achieves O(n) time.

⏱ Time O(n) Two passes — one to count, one to collect 💾 Space O(n) Freq map + bucket array both store n elements

Input: nums = [1,1,1,2,2,3], k = 2

StepState
Build freq map{1:3, 2:2, 3:1}
n = 6, create buckets[0..6]all empty
Fill bucketsbucket[3]=[1], bucket[2]=[2], bucket[1]=[3]
Scan from bucket[6] downbucket[6..4] empty
bucket[3] = [1]add 1, count=1
bucket[2] = [2]add 2, count=2=k, done
Return[1, 2]
function topKFrequent(nums, k):
freq = count all nums
buckets = array of (n+1) empty lists
for num, count in freq:
buckets[count].append(num)
result = []
for i from n down to 1:
result.extend(buckets[i])
if len(result) >= k:
return result[:k]
top_k_frequent_bucket_sort.py
from typing import List
from collections import Counter
def topKFrequent(nums: List[int], k: int) -> List[int]:
freq = Counter(nums)
n = len(nums)
buckets: List[List[int]] = [[] for _ in range(n + 1)]
for num, count in freq.items():
buckets[count].append(num)
result: List[int] = []
for i in range(n, 0, -1):
result.extend(buckets[i])
if len(result) >= k:
return result[:k]
return result[:k]
print(topKFrequent([1, 1, 1, 2, 2, 3], 2)) # [1, 2]
print(topKFrequent([1], 1)) # [1]
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
top_k_frequent_elements_space_optimized.py
"""
Solution for Top K Frequent Elements
"""
def solve():
"""Implementation for approach 3 of Top K Frequent Elements"""
pass
if __name__ == "__main__":
print("Solution ready")