Skip to content
Related Articles

Related Articles

Find K most occurring elements in the given Array

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 21 Sep, 2022
View Discussion
Improve Article
Save Article

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

Examples: 

Input: arr[] = {3, 1, 4, 4, 5, 2, 6, 1}, K = 2
Output: 4 1
Explanation:
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
Explanation: 
Frequency of 5 = 3, Frequency of 11 = 2, Frequency of 7 = 2, Frequency of 10 = 1
These four have the maximum frequency and 5 is largest among rest.

Find K most occurring elements in the given Array using Map

To solve the problem using this approach follow the below idea:

create a Map to store the element-frequency pair. Map is used to perform insertion and updation in constant time. Then sort the element-frequency pair in decreasing order of frequency. This gives the information about each element and the number of times they are present in the array. To get K elements of the array, print the first K elements of the sorted array.

Follow the given steps to solve the problem:

  • Create a map mp, to store key-value pair, i.e. element-frequency pair.
  • Traverse the array from start to end.
  • For every element in the array update mp[array[i]]++
  • Store the element-frequency pair in a vector and sort the vector in decreasing order of frequency.
  • Print the first k elements of the sorted array.

Below is the Implementation of the above approach:

C++




// C++ implementation to find k numbers with most
// occurrences in the given array
#include <bits/stdc++.h>
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;
}
 
// Function to print the k numbers with most occurrences
void print_N_mostFrequentNumber(int arr[], int N, int K)
{
    // unordered_map 'mp' implemented as frequency hash
    // table
    unordered_map<int, int> mp;
    for (int i = 0; i < N; i++)
        mp[arr[i]]++;
 
    // store the elements of 'mp' in the vector 'freq_arr'
    vector<pair<int, int> > freq_arr(mp.begin(), mp.end());
 
    // Sort the vector 'freq_arr' on the basis of the
    // 'compare' function
    sort(freq_arr.begin(), freq_arr.end(), compare);
 
    // display the top k numbers
    cout << K << " numbers with most occurrences are:\n";
    for (int i = 0; i < K; i++)
        cout << freq_arr[i].first << " ";
}
 
// Driver's code
int main()
{
    int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 2;
 
    // Function call
    print_N_mostFrequentNumber(arr, N, K);
 
    return 0;
}


Java




// Java implementation to find
// K elements with max occurrence.
 
import java.util.*;
public class KFrequentNumbers {
    static void print_N_mostFrequentNumber(int[] arr, int N,
                                           int K)
    {
 
        Map<Integer, Integer> mp
            = new HashMap<Integer, Integer>();
 
        // Put count of all the
        // distinct elements in Map
        // with element as the key &
        // count as the value.
        for (int i = 0; i < N; i++) {
 
            // Get the count for the
            // element if already present in the
            // Map or get the default value which is 0.
            mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1);
        }
 
        // Create a list from elements of HashMap
        List<Map.Entry<Integer, Integer> > list
            = new ArrayList<Map.Entry<Integer, Integer> >(
                mp.entrySet());
 
        // Sort the list
        Collections.sort(
            list,
            new Comparator<Map.Entry<Integer, Integer> >() {
                public int compare(
                    Map.Entry<Integer, Integer> o1,
                    Map.Entry<Integer, Integer> o2)
                {
                    if (o1.getValue() == o2.getValue())
                        return o2.getKey() - o1.getKey();
                    else
                        return o2.getValue()
                            - o1.getValue();
                }
            });
 
        for (int i = 0; i < K; i++)
            System.out.print(list.get(i).getKey() + " ");
    }
 
    // Driver's Code
    public static void main(String[] args)
    {
        int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 };
        int N = arr.length;
        int K = 2;
 
        // Function call
        System.out.println(
            K + " numbers with most occurrences are:");
        print_N_mostFrequentNumber(arr, N, K);
    }
}


Python3




# Python3 implementation to find k numbers
# with most occurrences in the given array
 
# Function to print the k numbers with
# most occurrences
 
 
def pr_N_mostFrequentNumber(arr, N, K):
 
    mp = {}
    for i in range(N):
        if arr[i] in mp:
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
    a = [0] * (len(mp))
    j = 0
    for i in mp:
        a[j] = [i, mp[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 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
 
    # Function call
    pr_N_mostFrequentNumber(arr, N, K)
 
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)


C#




// C# implementation to find
// k elements with max occurrence.
 
using System;
using System.Collections.Generic;
 
public class Comparer : IComparer<KeyValuePair<int, int> > {
    public int Compare(KeyValuePair<int, int> p2,
                       KeyValuePair<int, int> p1)
    {
        // If frequencies of two elements are same
        // then the larger number should come first
        if (p1.Value == p2.Value)
            return p1.Key.CompareTo(p2.Key);
 
        // Sort on the basis of decreasing order
        // of frequencies
        return p1.Value.CompareTo(p2.Value);
    }
}
 
public class KFrequentNumbers {
    static void print_N_mostFrequentNumber(int[] arr, int N,
                                           int K)
    {
 
        IDictionary<int, int> mp
            = new Dictionary<int, int>();
 
        // Put count of all the
        // distinct elements in Map
        // with element as the key &
        // count as the value.
        for (int i = 0; i < N; i++) {
 
            // Get the count for the
            // element if already present in the
            // Map or get the default value which is 0
            if (mp.ContainsKey(arr[i]))
                mp[arr[i]] += 1;
            else
                mp[arr[i]] = 1;
        }
 
        // Create a list from elements of HashMap
        List<KeyValuePair<int, int> > list
            = new List<KeyValuePair<int, int> >();
        foreach(KeyValuePair<int, int> entry in mp)
        {
            list.Add(entry);
        }
 
        // Sort the list
        Comparer compare = new Comparer();
        list.Sort(compare);
 
        for (int i = 0; i < K; i++)
            Console.Write(list[i].Key + " ");
    }
 
    // Driver's code
    public static void Main(string[] args)
    {
        int[] arr = { 3, 1, 4, 4, 5, 2, 6, 1 };
        int N = arr.Length;
        int K = 2;
 
        Console.Write(
            K + " elements with most occurrences are:\n");
 
        // Function call
        print_N_mostFrequentNumber(arr, N, K);
    }
}
 
// this code is contributed by phasing17


Javascript




// JavaScript implementation to find
// K elements with max occurrence.
 
function print_N_mostFrequentNumber(arr, N, K) {
 
    let mp = new Map();
 
    // Put count of all the
    // distinct elements in Map
    // with element as the key &
    // count as the value.
    for (let i = 0; i < N; i++) {
 
        // Get the count for the
        // element if already present in the
        // Map or get the default value which is 0.
 
        if (mp.has(arr[i])) {
            mp.set(arr[i], mp.get(arr[i]) + 1)
        } else {
            mp.set(arr[i], 1)
        }
    }
 
    // Create a list from elements of HashMap
    let list = [...mp];
 
    // Sort the list
    list.sort((o1, o2) => {
        if (o1[1] == o2[1])
            return o2[0] - o1[0];
        else
            return o2[1] - o1[1];
    })
 
    document.write(K + " numbers with most occurrences are: ");
    for (let i = 0; i < K; i++)
        document.write(list[i][0] + " ");
}
 
// Driver's Code
let arr = [3, 1, 4, 4, 5, 2, 6, 1];
let N = arr.length;
let K = 2;
 
// Function call
print_N_mostFrequentNumber(arr, N, K);


Output

2 numbers with most occurrences are:
4 1 

Time Complexity: O(D log D), 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

Find K most occurring elements in the given Array using Max-Heap 

To solve the problem using this approach follow the below idea:

Approach: Create a Map to store element-frequency pair. Map is used to perform insertion and updation in constant time. Then use a priority queue to store the element-frequency pair (Max-Heap). The element which has maximum frequency, comes at the root of the Priority Queue. Remove the top or root of Priority Queue K times and print the element.

Follow the given steps to solve the problem:

  • Create a map mp, to store key-value pair, i.e. element-frequency pair.
  • Traverse the array from start to end.
  • For every element in the array update mp[array[i]]++
  • Store the element-frequency pair in a Priority Queue
  • Run a loop k times, and in each iteration remove the root of the priority queue and print the element.

Below is the Implementation of the above approach:

C++




// C++ implementation to find k numbers with most
// occurrences in the given array
 
#include <bits/stdc++.h>
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;
    }
};
 
// Function to print the k numbers with most occurrences
void print_N_mostFrequentNumber(int arr[], int N, int K)
{
    // unordered_map 'mp' implemented as frequency hash
    // table
    unordered_map<int, int> mp;
    for (int i = 0; i < N; i++)
        mp[arr[i]]++;
 
    // 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<pair<int, int>, vector<pair<int, int> >,
                   compare>
        pq(mp.begin(), mp.end());
 
    // Display the top k numbers
    cout << K << " numbers with most occurrences are:\n";
    for (int i = 1; i <= K; i++) {
        cout << pq.top().first << " ";
        pq.pop();
    }
}
 
// Driver's code
int main()
{
    int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 2;
 
    // Function call
    print_N_mostFrequentNumber(arr, N, K);
    return 0;
}


Java




// Java implementation to find k
// elements with max occurrence.
import java.util.*;
public class KFrequentNumbers {
    static void print_N_mostFrequentNumber(int[] arr, int N,
                                           int K)
    {
        Map<Integer, Integer> mp
            = new HashMap<Integer, Integer>();
 
        // Put count of all the
        // distinct elements in Map
        // with element as the key &
        // count as the value.
        for (int i = 0; i < N; i++) {
 
            // Get the count for the
            // element if already
            // present in the Map or
            // get the default value
            // which is 0.
            mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1);
        }
 
        // Create a Priority Queue
        // to sort based on the
        // count or on the key if the
        // count is same
        PriorityQueue<Map.Entry<Integer, Integer> > queue
            = new PriorityQueue<>(
                (a, b)
                    -> a.getValue().equals(b.getValue())
                           ? Integer.compare(b.getKey(),
                                             a.getKey())
                           : Integer.compare(b.getValue(),
                                             a.getValue()));
 
        // Insert the data from the map
        // to the Priority Queue.
        for (Map.Entry<Integer, Integer> entry :
             mp.entrySet())
            queue.offer(entry);
 
        // Print the top k elements
        for (int i = 0; i < K; i++) {
            System.out.print(queue.poll().getKey() + " ");
        }
    }
 
    // Driver's Code
    public static void main(String[] args)
    {
        int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 };
        int N = arr.length;
        int K = 2;
 
        System.out.println(
            K + " numbers with most occurrences are:");
        // Function call
        print_N_mostFrequentNumber(arr, N, K);
    }
}
 
// This code is contributed by Shubham Kumar Shah


Python3




# Python3 implementation to find k
# numbers with most occurrences in
# the given array
import heapq
 
# Function to print the k numbers with
# most occurrences
 
 
def print_N_mostFrequentNumber(arr, N, K):
 
    mp = dict()
 
    # Put count of all the distinct elements
    # in dictionary with element as the
    # key & count as the value.
    for i in range(0, N):
        if arr[i] not in mp:
            mp[arr[i]] = 0
        else:
            mp[arr[i]] += 1
 
    # Using heapq data structure
    heap = [(value, key) for key,
            value in mp.items()]
 
    # Get the top k elements
    largest = heapq.nlargest(K, heap)
 
    # Insert the data from the map to
    # the priority queue
    print(K, " numbers with most "
             "occurrences are:", sep="")
 
    # Print the top k elements
    for i in range(K):
        print(largest[i][1], end=" ")
 
 
# Driver's code
if __name__ == "__main__":
 
    arr = [3, 1, 4, 4, 5, 2, 6, 1]
    N = len(arr)
    K = 2
 
    # Function call
    print_N_mostFrequentNumber(arr, N, K)
 
# This code is contributed by MuskanKalra1


C#




// C# implementation to find k
// elements with max occurrence.
 
using System;
using System.Collections.Generic;
using System.Linq;
 
public class KFrequentNumbers {
    static void print_N_mostFrequentNumber(int[] arr, int N,
                                           int K)
    {
        Dictionary<int, int> mp
            = new Dictionary<int, int>();
 
        // Put count of all the
        // distinct elements in Map
        // with element as the key &
        // count as the value.
        for (int i = 0; i < N; i++) {
 
            // Get the count for the
            // element if already
            // present in the Map or
            // get the default value
            // which is 0.
            if (!mp.ContainsKey(arr[i]))
                mp[arr[i]] = 0;
            mp[arr[i]]++;
        }
 
        // Create a Priority Queue
        // to sort based on the
        // count or on the key if the
        // count is same
        List<int> queue = mp.Keys.ToList();
        queue.Sort(delegate(int y, int x) {
            if (mp[x] == mp[y])
                return x.CompareTo(y);
            else
                return (mp[x]).CompareTo(mp[y]);
        });
 
        // Print the top k elements
        Console.WriteLine(
            K + " numbers with the most occurrences are:");
        for (int i = 0; i < K; i++) {
            Console.WriteLine(queue[i] + " ");
        }
    }
 
    // Driver's Code
    public static void Main(string[] args)
    {
        int[] arr = { 3, 1, 4, 4, 5, 2, 6, 1 };
        int N = arr.Length;
        int K = 2;
 
        // Function call
        print_N_mostFrequentNumber(arr, N, K);
    }
}
 
// This code is contributed by phasing17


Javascript




// Javascript implementation to find k
// elements with max occurrence.
 
function print_N_mostFrequentNumber(arr, N, K)
{   
    let mp = new Map();
    // Put count of all the
        // distinct elements in Map
        // with element as the key &
        // count as the value.
        for (let i = 0; i < N; i++) {
  
            // Get the count for the
            // element if already
            // present in the Map or
            // get the default value
            // which is 0.
            if(!mp.has(arr[i]))
                mp.set(arr[i],0);
             
            mp.set(arr[i],
                   mp.get(arr[i]) + 1);
        }
  
        // Create a Priority Queue
        // to sort based on the
        // count or on the key if the
        // count is same
        let queue=[...mp];
         
        queue.sort(function(a,b){
            if(a[1]==b[1])
            {
                return b[0]-a[0];
            }
            else
            {
                return b[1]-a[1];
            }
        });
         
        document.write(K + " numbers with most "+"occurrences are: ")
        for(let i=0; i<K; i++)
        {
            document.write(queue[i][0]+" ");
        }
}
 
// Driver's Code
let arr = [3, 1, 4, 4, 5, 2, 6, 1];
let N = arr.length;
let K = 2;
 
// Function call
print_N_mostFrequentNumber(arr, N, K);
 
// This code is contributed by avanitrachhadiya2155


Output

2 numbers with most occurrences are:
4 1 

Time Complexity: O(K log D + D log D), where D is the count of distinct elements in the array. 

  • To remove the top of the priority queue O(log d) time is required, so if k elements are removed then O(k log d) time is required, and 
  • To construct a priority queue with D elements, O(D log D) time is required.

Auxiliary Space: O(D), where D is the count of distinct elements in the array. 

Find K most occurring elements in the given Array using Bucket Sort

  • Create a HashMap elementCount and store the count of the elements in the given array.
  • Create a 2D vector frequency of size N+1 to store the elements according to their frequencies.
  • Now intilialize a variable count = 0.
  • While count < K:
    • Traverse the frequency vector from N till 0 and print the elements present in the vector and increment the count for each element.

Below is the implementation of above approach:

C++




// C++ program to find k numbers with most
// occurrences in the given array
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the k numbers with most occurrences
void print_N_mostFrequentNumber(int arr[], int N, int K)
{
    // HashMap to store count of the elements
    unordered_map<int, int> elementCount;
    for (int i = 0; i < N; i++) {
        elementCount[arr[i]]++;
    }
 
    // Array to store the elements according
    // to their frequency
    vector<vector<int> > frequency(N + 1);
 
    // Inserting elements in the frequency array
    for (auto element : elementCount) {
        frequency[element.second].push_back(element.first);
    }
 
    int count = 0;
    cout << K << " numbers with most occurrences are:\n";
 
    for (int i = frequency.size() - 1; i >= 0; i--) {
 
        for (auto element : frequency[i]) {
            count++;
            cout << element << " ";
        }
 
        // if K elements have been printed
        if (count == K)
            return;
    }
 
    return;
}
 
// Driver's code
int main()
{
    int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 2;
 
    // Function call
    print_N_mostFrequentNumber(arr, N, K);
 
    return 0;
}


Output

2 numbers with most occurrences are:
4 1 

Time Complexity: O(N), where N is the size of the given array.
Auxiliary Space: O(N)

This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!