Good evening! Here's our prompt for today.
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,
SNIPPET
1nums = [7, 11, 5, 5, 5, 11, 9]
2n = 4The 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.
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx28
var assert = require('assert');​function nMostFrequent(nums, n) { return;}​​try { assert.deepEqual(nMostFrequent([1, 1, 1, 2, 2, 3], 2), [1, 2]); console.log('PASSED: ' + "`nMostFrequent([1, 1, 1, 2, 2, 3])` should return `[1, 2]`");} catch (err) { console.log(err);}​try { assert.deepEqual(nMostFrequent([7, 11, 5, 5, 5, 11, 9], 4), [5, 11, 9, 7]); console.log('PASSED: ' + "`nMostFrequent([7, 11, 5, 5, 5, 11, 9])` should return `'[5, 11, 9, 7]`");} catch (err) { console.log(err);}​try { assert.deepEqual(nMostFrequent([3, 1, 4, 4, 5, 2, 6, 1], 2), [4, 1]); console.log('PASSED: ' + "`nMostFrequent([3, 1, 4, 4, 5, 2, 6, 1], 2)` should return `[4, 1]`");} catch (err) { console.log(err);}​OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's our guided, illustrated walk-through.
How do I use this guide?


