Top K Frequent Elements

Practice this coding question on Coding Gurukul.

Problem statement

A log contains repeated integer event codes. Select the k distinct codes occurring most frequently. Rank codes by decreasing frequency; when frequencies tie, the smaller numeric value ranks first. Print the selected codes in this ranking order so the answer is deterministic.

Input format

First line: n k. Second line: n integer event codes.

Output format

Print k distinct values ordered by decreasing frequency, breaking ties by increasing numeric value.

Constraints

1 <= n <= 100000; 1 <= k <= number of distinct values; -1000000000 <= each value <= 1000000000.

Sample input

6 2
1 1 1 2 2 3

Sample output

1 2

Sign in to run or submit a solution in C++, Java or Python.