All problems

Problem 97

Top K Frequent Elements

Medium · 20 pts · Array, Hash Table, Heap, Sorting

Problem

You are given an array of N integers and a number K. Print the K values that appear most often in the array. Order them by frequency, most frequent first. If two values appear the same number of times, print the smaller value first. K is never more than the number of distinct values. Count each value with a hash map, then sort the distinct values by (frequency descending, value ascending) and take the first K.

Input

First line: integers N and K. Second line: N space-separated integers.

Output

Print K values separated by spaces.

Constraints

1 <= N <= 100000; 1 <= K <= number of distinct values; -10000 <= A[i] <= 10000

Example input

6 2
1 1 1 2 2 3

Example output

1 2

Explanation

In 1 1 1 2 2 3, the value 1 appears 3 times, 2 appears twice and 3 once. The 2 most frequent values are 1 and then 2.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Kth Largest Element Next: Squares of a Sorted Array