← All coding problems
Top K Frequent Elements
mediumArrays & Hashing+20 XPTime limit 2s
Return the k values that appear most often in the array.
Input:
- line 1:
n k - line 2:
nintegers
Output: the k values on one line, most frequent first; when two values appear equally often, the smaller value comes first.
Constraints: 1 ≤ n ≤ 10⁵, −10⁴ ≤ a[i] ≤ 10⁴, 1 ≤ k ≤ number of distinct values.
Think about it: count with a hash map, then either sort the distinct values, use a heap of size k, or bucket them by frequency (O(n)).
Sample input 1
6 2 1 1 1 2 2 3
Sample output 1
1 2
Sample input 2
1 1 1
Sample output 2
1
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).