Find the k most frequent elements in an array using heaps and hash maps.
Imagine you’re analyzing data from a music streaming service. You want to find the top 3 most played songs from a playlist. That’s exactly what this problem helps us solve - finding the k most frequent elements in a list!
ID | Name | Difficulty |
---|---|---|
347 | Top K Frequent Elements | Medium |
692 | Top K Frequent Words | Medium |
703 | Kth Largest Element | Easy |
215 | Kth Largest Element in Array | Medium |
973 | K Closest Points to Origin | Medium |
Given an array of numbers and an integer k, return the k most frequent elements. You can return the answer in any order.
Let’s explore different ways to solve this problem using various programming languages:
from collections import Counter
import heapq
def topKFrequent(nums, k):
# Count frequencies
count = Counter(nums)
# Keep k most frequent elements using min-heap
heap = []
for num, freq in count.items():
heapq.heappush(heap, (freq, num))
if len(heap) > k:
heapq.heappop(heap)
# Extract results
return [num for freq, num in heap]
Let’s walk through the solution using a concrete example:
Input: nums = [1,1,1,2,2,3]
, k = 2
First, we count the frequencies of each number:
count = {1: 3, 2: 2, 3: 1}
Process each number-frequency pair through the heap:
Final result: [1,2]
- these are the two most frequent elements
Let’s analyze the efficiency of our solution:
Time Complexity: O(n log k)
Space Complexity: O(n)
This algorithm pattern is incredibly useful in various real-world scenarios:
Content Recommendations
System Monitoring
Data Analysis
To master this concept, try these related problems:
ID | Name | Difficulty |
---|---|---|
692 | Top K Frequent Words | Medium |
703 | Kth Largest Element | Easy |
215 | Kth Largest Element in Array | Medium |
973 | K Closest Points to Origin | Medium |
347 | Top K Frequent Elements | Medium |
Remember: The key to mastering these problems is understanding when to use hash maps for counting and heaps for maintaining top k elements efficiently.