📘
Top K Frequent Elements
MediumArrays & Hashing
Given an integer array and integer k, return the k most frequent elements in any order.
Output space-separated, sorted.
Example:
Input:
1,1,1,2,2,3 2
Output:
1 2
Reasoning:
- First, we count the frequency of each element in the array: 1 appears 3 times, 2 appears 2 times, and 3 appears 1 time.
- Then, we sort the elements by their frequency in descending order: 1 (3 times), 2 (2 times), 3 (1 time).
- Next, we select the top k=2 most frequent elements, which are 1 and 2.
- The final output is the selected elements in sorted order: 1 2
Constraints:
- 1 <= len(nums) <= 10^5
- -10^4 <= nums[i] <= 10^4
- k is always valid (1 <= k <= number of unique elements)
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.