Top K Frequent Elements - Problem
You're given an integer array nums and an integer k. Your task is to find the k most frequently occurring elements in the array and return them.
Goal: Identify which elements appear most often and return exactly k of them.
Example: In array [1,1,1,2,2,3] with k=2, element 1 appears 3 times and element 2 appears 2 times, so return [1,2].
Note: The answer can be returned in any order, and it's guaranteed that the answer is unique.
Input & Output
example_1.py โ Basic case with clear frequencies
$
Input:
nums = [1,1,1,2,2,3], k = 2
โบ
Output:
[1,2]
๐ก Note:
Element 1 appears 3 times (most frequent), element 2 appears 2 times (second most frequent), and element 3 appears 1 time. So the top 2 most frequent elements are 1 and 2.
example_2.py โ Single element array
$
Input:
nums = [1], k = 1
โบ
Output:
[1]
๐ก Note:
There's only one unique element, so it must be the most frequent (and only) element to return.
example_3.py โ All elements have same frequency
$
Input:
nums = [1,2,3,4,5], k = 3
โบ
Output:
[1,2,3] (or any 3 elements)
๐ก Note:
All elements appear exactly once, so any 3 elements form a valid answer since they all have the same frequency.
Visualization
Tap to expand
Understanding the Visualization
1
Count Song Plays
Like a radio station tracking how many times each song was played - use a hash map
2
Maintain Top K Chart
Instead of sorting all songs, use a min heap to efficiently maintain just the top k songs
3
Smart Filtering
When a new song is processed, only keep it if it's more popular than the least popular in our top k
4
Final Chart
Extract the k songs from our chart - these are the most frequent elements
Key Takeaway
๐ฏ Key Insight: Instead of sorting ALL songs by popularity (expensive), we maintain a small chart of just the top k songs using a min heap, making it perfect for scenarios where k is much smaller than the total number of unique elements!
Time & Space Complexity
Time Complexity
O(n log k)
O(n) to build frequency map + O(n log k) for heap operations (at most k elements in heap)
โก Linearithmic
Space Complexity
O(n + k)
O(n) for frequency map + O(k) for heap of size k
โก Linearithmic Space
Constraints
- 1 โค nums.length โค 105
- k is in the range [1, number of unique elements in the array]
- -104 โค nums[i] โค 104
- It is guaranteed that the answer is unique
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code