Print all array elements appearing more than N / K times (original) (raw)

Last Updated : 23 Jul, 2025

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 = 4
Output: 6
Explanation:
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++ `

// 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 / K void 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 Code int 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

// Java program to implement // the above approach import java.util.*;

class GFG{

// 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[] 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 Code public 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

Python3 program to implement

the above approach

Function to print all array elements

whose frequency is greater than N / K

def 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 Code

if 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#

// C# program to implement // the above approach
using System;

class GFG{

// 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);

// 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 Code public 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

JavaScript

`

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:

// C++ program to implement // the above approach

#include <bits/stdc++.h> using namespace std;

// Function to+ find the upper_bound of // an array element 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 void 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 Code int 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

// Java program to implement // the above approach import java.util.*; 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[]
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 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 shikhasingrajput

Python3

Python program to implement

the above approach

Function to+ find the upper_bound of

an array element

def 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 / K

def 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 Code

if 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 

JavaScript

C#

// C# program to implement // the above approach using 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

`

Time Complexity: O(N * log2N)
Auxiliary Space: O(1)

Another Approach: Using Built-in Python functions:

Below is the implementation:

C++ `

#include<bits/stdc++.h> using namespace std;

// Function to find the number of array // elements with frequency more than n/k times void printELements(vector arr, int n, int k){

// calculating n/k
int x = n/k;

// counting the frequency of every
// element using map data structure
map<int, int> mp;
for(int i = 0; i < n; i++){
    mp[arr[i]]++;
}

// Traverse the map and print all
// the elements with occurrence atleast 
// n/k times
for (auto it: mp){
    if(it.second > x){
        cout << it.first << endl;
    }
}

} int main(){ // Given array arr[] vector arr = {1, 2, 2, 6, 6, 6, 6, 7, 10};

// Size of array
int n = arr.size();
int k = 4;

printELements(arr, n, k);

return 0;

}

// This code is contributed by princekumaras

Java

// Java Code import java.io.; import java.util.;

class GFG {

// Function to find the number of array // elements with frequency more than n/k times static void printELements(int[] arr, int n, int k) {

// calculating n/k
int x = n/k;

// counting the frequency of every
// element using map data structure
HashMap<Integer, Integer> mp = new HashMap<>();
for(int i = 0; i < n; i++){
  if(mp.containsKey(arr[i]))
  {
    mp.put(arr[i],mp.get(arr[i])+1);
  }
  else
    mp.put(arr[i],1);
}

// Traverse the map and print all
// the elements with occurrence atleast
// n/k times
for (Map.Entry<Integer,Integer> it : mp.entrySet()){
  if(it.getValue() > x){
    System.out.println(it.getKey());
  }
}

} 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;

printELements(arr, n, k);

} }

// This code is contributed by Pushpesh Raj.

Python3

Python3 implementation

from collections import Counter

Function to find the number of array

elements with frequency more than n/k times

def 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 code

arr = [1, 2, 2, 6, 6, 6, 6, 7, 10]

Size of array

n = len(arr) k = 4

printElements(arr, n, k)

This code is contributed by vikkycirus

JavaScript

// Function to find the number of array // elements with frequency more than n/k times function printELements(arr, n, k) { // calculating n/k let x = n/k;

// counting the frequency of every
// element using map data structure
let mp=new Map();
for(let i = 0; i < n; i++)
{
    if(mp.has(arr[i]))
        mp.set(arr[i],mp.get(arr[i])+1);
    else
        mp.set(arr[i],1);
}

// Traverse the map and print all
// the elements with occurrence atleast 
// n/k times
mp.forEach((values,keys)=>{
    if(values > x){
        document.write(keys);
    }
})

} // Given array arr[] let arr = [1, 2, 2, 6, 6, 6, 6, 7, 10];

// Size of array let n = arr.length; let k = 4;

printELements(arr, n, k);

C#

using System; using System.Linq; using System.Collections.Generic;

class GFG { // Function to find the number of array // elements with frequency more than n/k times static void printELements(List arr, int n, int k) { // calculating n/k int x = n/k;

    // counting the frequency of every
    // element using map data structure
    Dictionary<int, int> mp=new Dictionary<int, int>();
    for(int i = 0; i < n; i++)
    {
        if(mp.ContainsKey(arr[i]))
        {
            var val = mp[arr[i]];
            mp.Remove(arr[i]);
            mp.Add(arr[i], val + 1);
        }
        else
            mp.Add(arr[i],1);
    }

    // Traverse the map and print all
    // the elements with occurrence atleast 
    // n/k times
    foreach(KeyValuePair<int, int> entry in mp)
    {
        if(entry.Value > x)
            Console.Write(entry.Key);
    }
}
static public void Main()
{
    // Given array arr[]
    List<int> arr = new List<int>{1, 2, 2, 6, 6, 6, 6, 7, 10};

    // Size of array
    int n = arr.Count;
    int k = 4;
    
    printELements(arr, n, k);
}

}

`

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)

Approach: Hashmap-Based Approach

The basic idea of this approach is to use a hashmap to store the frequency of each element in the array. Then, iterate through the hashmap and check if the frequency of any element is greater than (N / K). If yes, add that element to the list of required elements.

Algorithm:

  1. Create an empty hashmap freq_map to store the frequency of each element in the array.
  2. Traverse the array arr and insert each element of arr into freq_map, and increment its frequency by 1.
  3. Traverse the freq_map and for each key-value pair in the map, check if the value is greater than (N / K).
  4. If the value is greater than (N / K), then append the key to the list of required elements.
  5. Return the list of required elements. C++ `

#include #include #include

using namespace std;

vector find_elements(vector& arr, int K) { int N = arr.size(); unordered_map<int, int> freq_map; for (int i = 0; i < N; i++) { if (freq_map.find(arr[i]) == freq_map.end()) { freq_map[arr[i]] = 1; } else { freq_map[arr[i]]++; } } vector req_elements; for (auto& p : freq_map) { if (p.second > (N / K)) { req_elements.push_back(p.first); } } return req_elements; }

int main() { vector arr = { 1, 2, 6, 6, 6, 6, 6, 10 }; int K = 4; vector res = find_elements(arr, K); cout << "["; for (int i = 0; i < res.size(); i++) { cout << res[i]; if (i != res.size() - 1) { cout << ", "; } } cout << "]" << endl; return 0; }

Java

import java.io.; import java.util.;

public class GFG {

public static List<Integer> findElements(int[] arr, int K) {
    int N = arr.length;
    Map<Integer, Integer> freqMap = new HashMap<Integer, Integer>();
    
    // Finding frequency of each element in array
    for (int i = 0; i < N; i++) {
        if (!freqMap.containsKey(arr[i])) {
            freqMap.put(arr[i], 1);
        } else {
            freqMap.put(arr[i], freqMap.get(arr[i]) + 1);
        }
    }
    
    // Finding elements that appear more than N/K times in the array
    List<Integer> reqElements = new ArrayList<Integer>();
    for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {
        if (entry.getValue() > (N / K)) {
            reqElements.add(entry.getKey());
        }
    }
    return reqElements;
}

public static void main(String[] args) {
    int[] arr = {1, 2, 6, 6, 6, 6, 6, 10};
    int K = 4;
    List<Integer> result = findElements(arr, K);
    System.out.println(result); 
}

}

Python3

def find_elements(arr, K): N = len(arr) freq_map = {} for i in range(N): if arr[i] not in freq_map: freq_map[arr[i]] = 1 else: freq_map[arr[i]] += 1 req_elements = [] for key, value in freq_map.items(): if value > (N // K): req_elements.append(key) return req_elements

arr = [1, 2, 6, 6, 6, 6, 6, 10] K = 4 print(find_elements(arr, K)) # Output: [6]

This code is contributed by Uppala Sridevi

C#

using System; using System.Collections.Generic;

class Program { static List FindElements(List arr, int K) { int N = arr.Count; Dictionary<int, int> freq_map = new Dictionary<int, int>(); foreach (int i in arr) { if (!freq_map.ContainsKey(i)) { freq_map[i] = 1; } else { freq_map[i]++; } } List req_elements = new List(); foreach (KeyValuePair<int, int> p in freq_map) { if (p.Value > (N / K)) { req_elements.Add(p.Key); } } return req_elements; }

static void Main(string[] args)
{
    List<int> arr = new List<int>() { 1, 2, 6, 6, 6, 6, 6, 10 };
    int K = 4;
    List<int> res = FindElements(arr, K);
    Console.Write("[");
    for (int i = 0; i < res.Count; i++)
    {
        Console.Write(res[i]);
        if (i != res.Count - 1)
        {
            Console.Write(", ");
        }
    }
    Console.WriteLine("]");
}

}

JavaScript

function find_elements(arr, K) { let N = arr.length; let freq_map = new Map(); for (let i = 0; i < N; i++) { if (!freq_map.has(arr[i])) { freq_map.set(arr[i], 1); } else { freq_map.set(arr[i], freq_map.get(arr[i]) + 1); } } let req_elements = []; for (let [key, value] of freq_map) { if (value > Math.floor(N / K)) { req_elements.push(key); } } return req_elements; }

let arr = [1, 2, 6, 6, 6, 6, 6, 10]; let K = 4; let res = find_elements(arr, K); console.log(res);

`

Time Complexity: O(N), where N is the length of the array.
Auxiliary Space: O(N), to store the frequency of each element in the hashmap.