Back to questions
Given an integer array and an integer as input, return the top integers in the array (the ones that appear most frequently). Return the output in non-decreasing order. The test cases are generated in such a way that there will be a unique answer.
Input:
Output:
Explanation: The most frequent elements are: with a frequency of , with a frequency of , and with a frequency of . Finally, the output is sorted in non-decreasing order.
Input:
Output:
The first step in solving this problem is to count the frequency of each number using a dictionary.
Next, we need to sort the numbers based on their frequencies so that the most frequent numbers appear first.
If we sort only the frequencies, we will lose track of the actual numbers. To avoid this, we store each number along with its frequency as a pair (frequency, number) inside a list. Each element in this list will be another list of size , where:
Now, we sort this list. When sorting a list of lists, Python sorts based on the first element by default. Since we stored frequency first, numbers with lower frequencies will appear first.
To get the most frequent numbers first, we set in the function.
Finally, we take the first elements from this sorted list and extract only the second value (the actual number).
Here's the code to do that:
Instead of sorting, what if we group numbers based on their frequency?
We can do this in two ways:
Let’s analyze the second approach(using a list):
Here's the code to do that: