#C13085. Top K Frequent Elements

    ID: 42584 Type: Default 1000ms 256MiB

Top K Frequent Elements

Top K Frequent Elements

You are given a list of n integers and an integer k. Your task is to find the k most frequent elements in the list. The solution should employ a heap (or priority queue) structure to optimize space usage when selecting the top k elements. Note that the order of the output elements does not matter.

Detailed Explanation:

  • Compute the frequency of each input element.
  • Use a heap to extract the k elements with the highest frequency. In case of ties, the order is determined by the order of first appearance in the input.
  • If the input array is empty or if k is less than or equal to 0, output an empty result.

Mathematical Formulation:

Let \(A = [a_1, a_2, \dots, a_n]\) be the input list. Define \(f(x) = \text{number of occurrences of } x \text{ in } A\). We must output any set \(S\) such that \(|S| = k\) and for every \(x \in S\) and every \(y \notin S\), \(f(x) \ge f(y)\).

inputFormat

The input is read from standard input (stdin) and follows this format:

  1. The first line contains two integers n and k, where n represents the number of elements in the list and k is the number of top frequent elements to output.
  2. The second line contains n integers separated by spaces.

If n is 0, the second line will be empty, and the output should be empty.

outputFormat

Print to standard output (stdout) a single line containing the k most frequent elements separated by a single space. The order of the elements does not matter. If there are no elements to output, print an empty line.

## sample
12 2
1 1 1 2 2 3 3 3 4 4 4 4
4 1