Most Frequent Values
Given an integer array nums and an integer k, return the k values that occur most often.
Order the result by frequency, highest first. When two values have the same frequency, the smaller value comes first. k is never larger than the number of distinct values.
Example 1
Input: nums = [4, 4, 4, 2, 2, 9], k = 2 Output: [4, 2]
Example 2
Input: nums = [5, 3, 5, 3, 1], k = 2 Output: [3, 5] Explanation: 3 and 5 both appear twice; 3 is smaller.
Constraints
- 1 <= nums.length <= 10^5
- 1 <= k <= number of distinct values
Hint 1
Count occurrences with a map.
Hint 2
Sort the (value, count) pairs by count descending, then value ascending.
Good practice for: Data Scientist, Data Engineer, Machine Learning Engineer, AI Engineer (LLM & Generative AI), Backend Developer, Full Stack Developer, Site Reliability Engineer
Run checks your code on 2 sample tests. Submit runs all 7 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.