Print all array elements appearing more than N / K times

11 Mar, 2022
Given an array arr[] of size N and an integer K, the task is to find all the array elements that appear more than (N / K) times.
Examples:
Input: arr[] = { 1, 2, 6, 6, 6, 6, 6, 10 }, K = 4Output: 6Explanation: The frequency of 6 in the array is greater than N / K(= 2). Therefore, the required output is 6.
Input: arr[] = { 3, 4, 4, 5, 5, 5, 5 }, K = 4 Output: 4 5 Explanation: The frequency of 4 in the array is greater than N / K(= 1). The frequency of 5 in the array is greater than N / K(= 1). Therefore, the required output is 4 5.
Naive Approach: The simplest approach to solve this problem is to traverse the array and for every distinct array element, count its frequency and check if exceeds N / K or not. If found to be true, then print the array element. 
Time Complexity: O(N2)Auxiliary Space: O(1)
Sorting-based Approach: The idea is to sort the array followed by traversal of the array to count the frequency of every distinct array element by checking if adjacent elements are equal or not. If frequency of the array element is found to be greater than N / K, then print the array element.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to print all array elements// whose frequency is greater than N / Kvoid NDivKWithFreq(int arr[], int N, int K){    // Sort the array, arr[]    sort(arr, arr + N);     // Traverse the array    for (int i = 0; i < N;) {         // Stores frequency of arr[i]        int cnt = 1;         // Traverse array elements which        // is equal to arr[i]        while ((i + 1) < N               && arr[i] == arr[i + 1]) {             // Update cnt            cnt++;             // Update i            i++;        }         // If frequency of arr[i] is        // greater than (N / K)        if (cnt > (N / K)) {             cout << arr[i] << " ";        }        i++;    }} // Driver Codeint main(){    int arr[] = { 1, 2, 2, 6, 6, 6, 6, 7, 10 };    int N = sizeof(arr) / sizeof(arr[0]);    int K = 4;     NDivKWithFreq(arr, N, K);     return 0;}
// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to print all array elements// whose frequency is greater than N / Kstatic void NDivKWithFreq(int arr[], int N, int K){    // Sort the array, arr[]    Arrays.sort(arr);     // Traverse the array    for (int i = 0; i < N;) {         // Stores frequency of arr[i]        int cnt = 1;         // Traverse array elements which        // is equal to arr[i]        while ((i + 1) < N               && arr[i] == arr[i + 1]) {             // Update cnt            cnt++;             // Update i            i++;        }         // If frequency of arr[i] is        // greater than (N / K)        if (cnt > (N / K)) {             System.out.print(arr[i]+ " ");        }        i++;    }} // Driver Codepublic static void main(String[] args){    int arr[] = { 1, 2, 2, 6, 6, 6, 6, 7, 10 };    int N = arr.length;    int K = 4;     NDivKWithFreq(arr, N, K);}} // This code is contributed by 29AjayKumar
# Python3 program to implement# the above approach # Function to print all array elements# whose frequency is greater than N / Kdef NDivKWithFreq(arr, N, K):         # Sort the array, arr[]    arr = sorted(arr)     # Traverse the array    i = 0         while i < N:                 # Stores frequency of arr[i]        cnt = 1         # Traverse array elements which        # is equal to arr[i]        while ((i + 1) < N and               arr[i] == arr[i + 1]):             # Update cnt            cnt += 1             # Update i            i += 1         # If frequency of arr[i] is        # greater than (N / K)        if (cnt > (N // K)):            print(arr[i], end = " ")                     i += 1 # Driver Codeif __name__ == '__main__':         arr = [ 1, 2, 2, 6, 6, 6, 6, 7, 10 ]    N = len(arr)    K = 4     NDivKWithFreq(arr, N, K) # This code is contributed by mohit kumar 29
// C# program to implement// the above approach using System;    class GFG{    // Function to print all array elements// whose frequency is greater than N / Kstatic void NDivKWithFreq(int[] arr, int N,                          int K){         // Sort the array, arr[]    Array.Sort(arr);      // Traverse the array    for(int i = 0; i < N;)    {                 // Stores frequency of arr[i]        int cnt = 1;          // Traverse array elements which        // is equal to arr[i]        while ((i + 1) < N &&               arr[i] == arr[i + 1])        {                         // Update cnt            cnt++;              // Update i            i++;        }          // If frequency of arr[i] is        // greater than (N / K)        if (cnt > (N / K))        {            Console.Write(arr[i] + " ");        }        i++;    }}    // Driver Codepublic static void Main(){    int[] arr = { 1, 2, 2, 6, 6, 6, 6, 7, 10 };    int N = arr.Length;    int K = 4;      NDivKWithFreq(arr, N, K);}} // This code is contributed by code_hunt
<script> // JavaScript program for above approach // Function to print all array elements// whose frequency is greater than N / Kfunction NDivKWithFreq(arr, N, K){    // Sort the array, arr[]    arr.sort();      // Traverse the array    for (let i = 0; i < N;) {          // Stores frequency of arr[i]        let cnt = 1;          // Traverse array elements which        // is equal to arr[i]        while ((i + 1) < N               && arr[i] == arr[i + 1]) {              // Update cnt            cnt++;              // Update i            i++;        }          // If frequency of arr[i] is        // greater than (N / K)        if (cnt > (N / K)) {              document.write(arr[i]+ " ");        }        i++;    }}  // Driver Code     let arr = [1, 2, 2, 6, 6, 6, 6, 7, 10 ];    let N = arr.length;    let K = 4;      NDivKWithFreq(arr, N, K);           </script>
6
 
Time Complexity: O(N * log2N)Auxiliary Space: O(1)
Binary Search-Based Approach: The problem can be solved using Binary Search technique. The idea is to traverse the array and count the frequency of every distinct array element by calculating the upper bound of array elements. Finally, check if the frequency of the array element is greater than N / K or not. If found to be true, then print the array element. Follow the steps below to solve the problem:
Sort the array, arr[].
Traverse the array using the variable i and find the upper_bound of arr[i] say, X and check if (x – i) is greater than N / K or not. If found to be true then print the arr[i].
Finally, update i = X.
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to+ find the upper_bound of// an array elementint upperBound(int arr[], int N, int K){     // Stores minimum index    // in which K lies    int l = 0;     // Stores maximum index    // in which K lies    int r = N;     // Calculate the upper    // bound of K    while (l < r) {         // Stores mid element        // of l and r        int mid = (l + r) / 2;         // If arr[mid] is less        // than or equal to K        if (arr[mid] <= K) {             // Right subarray            l = mid + 1;        }         else {             // Left subarray            r = mid;        }    }    return l;} // Function to print all array elements// whose frequency is greater than N / Kvoid NDivKWithFreq(int arr[], int N, int K){     // Sort the array arr[]    sort(arr, arr + N);     // Stores index of    // an array element    int i = 0;     // Traverse the array    while (i < N) {         // Stores upper bound of arr[i]        int X = upperBound(arr, N, arr[i]);         // If frequency of arr[i] is        // greater than N / 4        if ((X - i) > N / 4) {             cout << arr[i] << " ";        }         // Update i        i = X;    }} // Driver Codeint main(){    // Given array arr[]    int arr[] = { 1, 2, 2, 6, 6, 6, 6, 7, 10 };     // Size of array    int N = sizeof(arr) / sizeof(arr[0]);     int K = 4;     // Function Call    NDivKWithFreq(arr, N, K);     return 0;}
// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to+ find the upper_bound of// an array elementstatic int upperBound(int arr[], int N, int K){     // Stores minimum index    // in which K lies    int l = 0;     // Stores maximum index    // in which K lies    int r = N;     // Calculate the upper    // bound of K    while (l < r)    {         // Stores mid element        // of l and r        int mid = (l + r) / 2;         // If arr[mid] is less        // than or equal to K        if (arr[mid] <= K)        {             // Right subarray            l = mid + 1;        }         else        {             // Left subarray            r = mid;        }    }    return l;} // Function to print all array elements// whose frequency is greater than N / Kstatic void NDivKWithFreq(int arr[], int N, int K){     // Sort the array arr[]    Arrays.sort(arr);     // Stores index of    // an array element    int i = 0;     // Traverse the array    while (i < N)    {         // Stores upper bound of arr[i]        int X = upperBound(arr, N, arr[i]);         // If frequency of arr[i] is        // greater than N / 4        if ((X - i) > N / 4)        {             System.out.print(arr[i] + " ");        }         // Update i        i = X;    }} // Driver Codepublic static void main(String[] args){    // Given array arr[]    int arr[] = { 1, 2, 2, 6, 6, 6, 6, 7, 10 };     // Size of array    int N = arr.length;    int K = 4;     // Function Call    NDivKWithFreq(arr, N, K);}} // This code is contributed by shikhasingrajput
# Python program to implement# the above approach # Function to+ find the upper_bound of# an array elementdef upperBound(arr, N, K):   # Stores minimum index    # in which K lies    l = 0;     # Stores maximum index    # in which K lies    r = N;     # Calculate the upper    # bound of K    while (l < r):         # Stores mid element        # of l and r        mid = (l + r) // 2;         # If arr[mid] is less        # than or equal to K        if (arr[mid] <= K):             # Right subarray            l = mid + 1;        else:             # Left subarray            r = mid;    return l; # Function to print all array elements# whose frequency is greater than N / Kdef NDivKWithFreq(arr, N, K):     # Sort the array arr    arr.sort();     # Stores index of    # an array element    i = 0;     # Traverse the array    while (i < N):         # Stores upper bound of arr[i]        X = upperBound(arr, N, arr[i]);         # If frequency of arr[i] is        # greater than N / 4        if ((X - i) > N // 4):            print(arr[i], end="");         # Update i        i = X; # Driver Codeif __name__ == '__main__':       # Given array arr    arr = [1, 2, 2, 6, 6, 6, 6, 7, 10];     # Size of array    N = len(arr);    K = 4;     # Function Call    NDivKWithFreq(arr, N, K);     # This code is contributed by 29AjayKumar
// C# program to implement// the above approachusing System;class GFG{   // Function to+ find the upper_bound of  // an array element  static int upperBound(int []arr, int N, int K)  {     // Stores minimum index    // in which K lies    int l = 0;     // Stores maximum index    // in which K lies    int r = N;     // Calculate the upper    // bound of K    while (l < r)    {       // Stores mid element      // of l and r      int mid = (l + r) / 2;       // If arr[mid] is less      // than or equal to K      if (arr[mid] <= K)      {         // Right subarray        l = mid + 1;      }       else      {         // Left subarray        r = mid;      }    }    return l;  }   // Function to print all array elements  // whose frequency is greater than N / K  static void NDivKWithFreq(int []arr, int N, int K)  {     // Sort the array arr[]    Array.Sort(arr);     // Stores index of    // an array element    int i = 0;     // Traverse the array    while (i < N)    {       // Stores upper bound of arr[i]      int X = upperBound(arr, N, arr[i]);       // If frequency of arr[i] is      // greater than N / 4      if ((X - i) > N / 4)      {         Console.Write(arr[i] + " ");      }       // Update i      i = X;    }  }   // Driver Code  public static void Main(string[] args)  {     // Given array arr[]    int []arr = { 1, 2, 2, 6, 6, 6, 6, 7, 10 };     // Size of array    int N = arr.Length;    int K = 4;     // Function Call    NDivKWithFreq(arr, N, K);  }} // This code is contributed by AnkThon
<script>// Javascript program to implement// the above approach //function to sort the arrayfunction sort(number){var n= number.length;    for (i = 0; i < n; ++i)        {             for (j = i + 1; j < n; ++j)            {                 if (number[i] > number[j])                {                     a =  number[i];                    number[i] = number[j];                    number[j] = a;                 }             }         }} // Function to find the upper_bound of// an array elementfunction upperBound( arr, N, K){     // Stores minimum index    // in which K lies    var l = 0;     // Stores maximum index    // in which K lies    var r = N;     // Calculate the upper    // bound of K    while (l < r) {         // Stores mid element        // of l and r        var mid = parseInt((l + r) / 2);         // If arr[mid] is less        // than or equal to K        if (arr[mid] <= K) {             // Right subarray            l = mid + 1;        }         else {             // Left subarray            r = mid;        }    }    return l;} // Function to print all array elements// whose frequency is greater than N / Kfunction NDivKWithFreq(arr, N, K){     // Sort the array arr[]    sortt(arr);     // Stores index of    // an array element    var i = 0;     // Traverse the array    while (i < N) {         // Stores upper bound of arr[i]        var X = upperBound(arr, N, arr[i]);         // If frequency of arr[i] is        // greater than N / 4        if ((X - i) > parseInt(N / 4)) {             document.write( arr[i] + " ");        }         // Update i        i = X;    }}     // Given array arr[]    var arr = [ 1, 2, 2, 6, 6, 6, 6, 7, 10 ];     // Size of array    var N = arr.length;     var K = 4;     // Function Call    NDivKWithFreq(arr, N, K); //This code in contributed by SoumikMondal</script>
6
 
Time Complexity: O(N * log2N)Auxiliary Space: O(1)
Count the frequencies of every element using Counter() function.
Traverse the frequency array and print all the elements which occur at more than n/k times.
Below is the implementation:
Python3
# Python3 implementationfrom collections import Counter # Function to find the number of array# elements with frequency more than n/k timesdef printElements(arr, n, k):     # Calculating n/k    x = n//k     # Counting frequency of every    # element using Counter    mp = Counter(arr)         # Traverse the map and print all    # the elements with occurrence atleast n/k times    for it in mp:        if mp[it] > x:            print(it)  # Driver codearr = [1, 2, 2, 6, 6, 6, 6, 7, 10] # Size of arrayn = len(arr)k = 4 printElements(arr, n, k) # This code is contributed by vikkycirus
Output:
6
Time Complexity: O(N)
Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach, the idea is to store the frequency of each distinct array element into a Map. Finally, traverse the map and check if its frequency is greater than (N / K) or not. If found to be true, then print the array element. Refer to this article for the discussion of this approach. 
Time Complexity: O(N)Auxiliary Space: O(N)
mohit kumar 29
29AjayKumar
code_hunt
shikhasingrajput
ankthon
vikkycirus
avijitmondal1998
SoumikMondal
anikaseth98
ankita_saini
adnanirshad158
sumitgumber28
Arrays
Binary Search
cpp-map
Arrays
C++ Programs
Divide and Conquer
Greedy
Hash
Sorting
Arrays
Hash
Greedy
Divide and Conquer
Sorting
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++