Loading problem…
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Example 1
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Explanation: 1 appears 3 times and 2 appears 2 times, making them the two most frequent. 3 appears only once.
Example 2
Input: nums = [1], k = 1
Output: [1]
Explanation: The only element is the most frequent one.
Example 3
Input: nums = [1,2], k = 2
Output: [1,2]
Explanation: k = 2 and there are only two distinct values, so both are returned.
Count frequencies with a hash map, then use bucket sort where index = frequency. Walk buckets from high to low to collect top k.
Run checks all cases above. Submit evaluates all test cases.