#K12726. K Most Frequent Elements

    ID: 23755 Type: Default 1000ms 256MiB

K Most Frequent Elements

K Most Frequent Elements

You are given an array of integers and an integer k. Your task is to find the k most frequent elements in the array, while preserving their original order of appearance. In other words, if two elements have the same frequency, the one that appears first in the array should be output first.

Formally, let the frequency of an element x be denoted as \(f(x)\). You need to output the first \(k\) elements from the sorted order of unique elements based on the criteria:

  • Higher frequency first, i.e., if \(f(x) > f(y)\), then x comes before y.
  • If \(f(x) = f(y)\), the element that appears earlier in the input comes first.

If k is 0 or if the array is empty, output nothing.

inputFormat

The input is read from standard input and has the following format:

n k
a1 a2 a3 ... an

Here, n is the number of elements in the array, k is the number of most frequent elements to output, and a1, a2, ..., an are the elements of the array. If n is 0, the second line may be empty.

outputFormat

Print the k most frequent elements in order, separated by a single space. Output should be printed to standard output. If no element is to be output, print nothing.

## sample
6 2
1 1 1 2 2 3
1 2

</p>