Top K Frequent Elements
Problem Statement
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Constraints:
- 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]
- It is guaranteed that the answer is unique.
Input Format:
- An integer array nums
- An integer k
Output Format:
- Return the k most frequent elements in any order.
Examples:
Example 1:
Input:
nums = [1,1,1,2,2,3], k = 2
Output:
[1,2]
Explanation:
The elements 1 and 2 appear the most frequently. 1 appears 3 times and 2 appears 2 times.
Example 2:
Input:
nums = [1], k = 1
Output:
[1]
Explanation:
The element 1 appears once, which is the only element in the array.
Solutions
Hash Map and Heap Approach
Count the frequency of each element using a hash map. Then use a min-heap of size k to keep track of the k most frequent elements.
Bucket Sort Approach
Count the frequency of each element using a hash map. Then use bucket sort where the bucket index represents the frequency. Iterate through the buckets from highest to lowest frequency to find the top k elements.
Algorithm Walkthrough
Example input: nums = [1,1,1,2,2,3]
Step-by-step execution:
- Count frequencies: {1: 3, 2: 2, 3: 1}
- Create bucket sort array with indices as frequencies: [[], [3], [2], [1], [], []]
- Start from highest frequency (bucket[3]): Add 1 to result. result = [1]
- Move to next highest (bucket[2]): Add 2 to result. result = [1, 2]
- We've found k=2 elements, so return [1, 2]
Hints
Hint 1
Hint 2
Hint 3
Hint 4
Video Tutorial
Video tutorials can be a great way to understand algorithms visually
Visualization
Visualize the frequency of each element in the array, and how the top k elements are selected.
Key visualization elements:
- frequency counting
- selection process
Implementation Notes
This problem tests knowledge of frequency counting, sorting, and data structures like heaps. It's a common interview question that can be solved with multiple approaches, each with different trade-offs.