# Find k numbers with most occurrences in the given array

Given an array of n numbers and a positive integer k. The problem is to find k numbers with most occurrences, i.e., the top k numbers having the maximum frequency. If two numbers have same frequency then the larger number should be given preference. The numbers should be displayed in decreasing order of their frequencies. It is assumed that the array consists of k numbers with most occurrences.

Examples:

```Input : arr[] = {3, 1, 4, 4, 5, 2, 6, 1},
k = 2
Output : 4 1
Frequency of 4 = 2
Frequency of 1 = 2
These two have the maximum frequency and
4 is larger than 1.

Input : arr[] = {7, 10, 11, 5, 2, 5, 5, 7, 11, 8, 9},
k = 4
Output : 5 11 7 10
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Method 1: Using hash table, we create a frequency table which stores the frequency of occurrence of each number in the given array. In the hash table we define (x, y) tuple, where x is the key(number) and y is its frequency in the array. Now we traverse this hash table and create an array freq_arr[] which stores these (number, frequency) tuples. Sort this freq_arr[] on the basis of the conditions defined in the problem statement. Now, print the first k numbers of this freq_arr[].

## C++

 `// C++ implementation to find k numbers with most ` `// occurrences in the given array ` `#include ` ` `  `using` `namespace` `std; ` ` `  `// comparison function to sort the 'freq_arr[]' ` `bool` `compare(pair<``int``, ``int``> p1, pair<``int``, ``int``> p2) ` `{ ` `    ``// if frequencies of two elements are same ` `    ``// then the larger number should come first ` `    ``if` `(p1.second == p2.second) ` `        ``return` `p1.first > p2.first; ` `         `  `    ``// sort on the basis of decreasing order ` `    ``// of frequencies     ` `    ``return` `p1.second > p2.second;     ` `} ` ` `  `// funnction to print the k numbers with most occurrences ` `void` `print_N_mostFrequentNumber(``int` `arr[], ``int` `n, ``int` `k) ` `{ ` `    ``// unordered_map 'um' implemented as frequency hash table ` `    ``unordered_map<``int``, ``int``> um; ` `    ``for` `(``int` `i = 0; i > freq_arr(um.begin(), um.end()); ` `     `  `    ``// sort the vector 'freq_arr' on the basis of the ` `    ``// 'compare' function ` `    ``sort(freq_arr.begin(), freq_arr.end(), compare); ` `     `  `    ``// display the the top k numbers ` `    ``cout << k << ````" numbers with most occurrences are: "````; ` `    ``for` `(``int` `i = 0; i

## Python3

# Python3 implementation to find k numbers
# with most occurrences in the given array

# funnction to pr the k numbers with
# most occurrences
def pr_N_mostFrequentNumber(arr, n, k):

um = {}
for i in range(n):
if arr[i] in um:
um[arr[i]] += 1
else:
um[arr[i]] = 1
a = [0] * (len(um))
j = 0
for i in um:
a[j] = [i, um[i]]
j += 1
a = sorted(a, key = lambda x : x[0],
reverse = True)
a = sorted(a, key = lambda x : x[1],
reverse = True)

# display the the top k numbers
print(k, “numbers with most occurrences are:”)
for i in range(k):
print(a[i][0], end = ” “)

# Driver code
if __name__ ==”__main__”:
arr = [3, 1, 4, 4, 5, 2, 6, 1]
n = 8
k = 2
pr_N_mostFrequentNumber(arr, n, k)

# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)

Output:

```2 numbers with most occurrences are:
4 1
```

Time Complexity: O(dlogd), where d is the count of distinct elements in the array.
Auxiliary Space: O(d), where d is the count of distinct elements in the array.

Method 2: Create the array freq_arr[] as described in Method 1 of this post. Now, build the max heap using elements of this freq_arr[]. The root of the max heap should be the most frequent number and in case of conflicts the larger number gets the preference. Now remove the top k numbers of this max heap. C++ STL priority_queue has been used as max heap.

 `// C++ implementation to find k numbers with most ` `// occurrences in the given array ` `#include ` ` `  `using` `namespace` `std; ` ` `  `// comparison function defined for the priority queue ` `struct` `compare ` `{ ` `    ``bool` `operator()(pair<``int``, ``int``> p1, pair<``int``, ``int``> p2) ` `    ``{ ` `        ``// if frequencies of two elements are same ` `        ``// then the larger number should come first ` `        ``if` `(p1.second == p2.second) ` `            ``return` `p1.first < p2.first; ` `             `  `        ``// insert elements in the priority queue on the basis of ` `        ``// decreasing order of frequencies     ` `        ``return` `p1.second < p2.second;     ` `    ``} ` `}; ` ` `  `// funnction to print the k numbers with most occurrences ` `void` `print_N_mostFrequentNumber(``int` `arr[], ``int` `n, ``int` `k) ` `{ ` `    ``// unordered_map 'um' implemented as frequency hash table ` `    ``unordered_map<``int``, ``int``> um; ` `    ``for` `(``int` `i = 0; i > freq_arr(um.begin(), um.end()); ` `     `  `    ``// priority queue 'pq' implemented as max heap on the basis ` `    ``// of the comparison operator 'compare' ` `    ``// element with the highest frequency is the root of 'pq' ` `    ``// in case of conflicts, larger element is the root ` `    ``priority_queue, vector >,  ` `                           ``compare> pq(um.begin(), um.end()); ` `     `  `    ``// display the the top k numbers ` `    ``cout << k << ````" numbers with most occurrences are: "````; ` `    ``for` `(``int` `i = 1; i<= k; i++) ` `    ``{ ` `        ``cout << pq.top().first << ``" "``; ` `        ``pq.pop(); ` `    ``}             ` `} ` ` `  `// Driver program to test above ` `int` `main() ` `{ ` `    ``int` `arr[] = {3, 1, 4, 4, 5, 2, 6, 1}; ` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]); ` `    ``int` `k = 2; ` `    ``print_N_mostFrequentNumber(arr, n, k); ` `    ``return` `0; ` `} `

Output:

```2 numbers with most occurrences are:
4 1
```

Time Complexity: O(klogd), where d is the count of distinct elements in the array.
Auxiliary Space: O(d), where d is the count of distinct elements in the array.