Most frequent numbers
MediumStuck?
Show a hintHide the hint
Count how many times each number appears, then order those counts and take the first k. Ties go to the smaller number.
The ideas behind this problem
Next in this lesson
Merging many sorted lists at onceGiven a list of numbers and a value k, return the k numbers that appear most often, in decreasing order of how often they appear. Where two numbers appear equally often, the smaller number comes first.
Worked example#
For [1, 1, 1, 2, 2, 3] with k = 2, count first:
| number | times |
|---|---|
| 1 | 3 |
| 2 | 2 |
| 3 | 1 |
Sorted by count, highest first: 1, then 2, then 3. Taking the first two gives [1, 2].
Two steps: count, then take the largest counts. Counting is a hash map. Taking the largest few can be a sort, or a heap when k is much smaller than the number of distinct values.
Constraints#
1 <= n <= 1000001 <= k <= number of distinct values
Input
nums is a count then that many integers. k is one integer.
Output
The k most frequent numbers, separated by spaces.
Examples
Input
6 1 1 1 2 2 3 2
Output
1 2
1 appears three times and 2 appears twice, so those are the top two.
Input
1 1 1
Output
1
One number, one answer.
Input
5 3 3 1 1 2 2
Output
1 3
1 and 3 both appear twice, so the smaller one comes first.
Something wrong with this problem? Report an issue
Ready to try it
Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.
Free, and it stays free. No card.