Mark As Completed Discussion

Good afternoon! 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.

Question

For example, consider the following array,

SNIPPET
1nums = [7, 11, 5, 5, 5, 11, 9]
2n = 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
  • n is 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?

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

We'll now take you through what you need to know.

How do I use this guide?

Access all course materials today

The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.

Returning members can login to stop seeing this.