Back to DSA sheet
Top K Frequent Elements
MediumArraysGiven an integer array, return the k most frequent elements. The answer is unique. Output them in ascending order for a deterministic result.
Input format (stdin): the first line has n and k. The second line has n integers. Output the k most frequent values, ascending, space separated.
Examples
Input: 6 2
1 1 1 2 2 3
Output: 1 2
1 (x3) and 2 (x2) are most frequent.
Input: 1 1
1
Output: 1
Constraints
- 1 <= n <= 10^5
- k is in [1, number of distinct values]
Sheets
Blind 75NeetCode 150NeetCode 250
top-k-frequent-elements.cpp3 sample tests
Loading editor
Test results
Run the sample tests to check your solution against expected output.
Custom input (stdin)
Output
Run your code to see its output.