N Most Frequent Elements
Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.
Question
Consider that you are given an integer array nums and an integer n. Find the n most frequent elements in the nums array. If two numbers have the same frequency, then the number with a larger value should be given preference.

For example, consider the following array,
nums = [7, 11, 5, 5, 5, 11, 9]
n = 4
The number 5 occurs in the array thrice, and 11 and 7 both appear twice. Each of the remaining numbers occurs only once. There are four unique numbers in the array, so all of them will be in the output list. But they will be ordered according to higher frequency and values. The answer would then be [5, 11, 9, 7].
Constraints
- 1 <=
nums.length<= 105 - -104 <=
nums[i]<= 104 -
nis in the range [1, the number of unique elements in the array]. - It is guaranteed that the answer is unique.
CONTINUE WITH ALGODAILY PREMIUM
Keep going with the complete tutorial.
Unlock the remaining explanations and exercises, alongside the full learning library.
Explore Premium →