Print all array elements appearing more than N / K times
Last Updated :
11 May, 2023
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++
#include <bits/stdc++.h>
using namespace std;
void NDivKWithFreq( int arr[], int N, int K)
{
sort(arr, arr + N);
for ( int i = 0; i < N;) {
int cnt = 1;
while ((i + 1) < N
&& arr[i] == arr[i + 1]) {
cnt++;
i++;
}
if (cnt > (N / K)) {
cout << arr[i] << " " ;
}
i++;
}
}
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
import java.util.*;
class GFG{
static void NDivKWithFreq( int arr[], int N, int K)
{
Arrays.sort(arr);
for ( int i = 0 ; i < N;) {
int cnt = 1 ;
while ((i + 1 ) < N
&& arr[i] == arr[i + 1 ]) {
cnt++;
i++;
}
if (cnt > (N / K)) {
System.out.print(arr[i]+ " " );
}
i++;
}
}
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);
}
}
|
Python3
def NDivKWithFreq(arr, N, K):
arr = sorted (arr)
i = 0
while i < N:
cnt = 1
while ((i + 1 ) < N and
arr[i] = = arr[i + 1 ]):
cnt + = 1
i + = 1
if (cnt > (N / / K)):
print (arr[i], end = " " )
i + = 1
if __name__ = = '__main__' :
arr = [ 1 , 2 , 2 , 6 , 6 , 6 , 6 , 7 , 10 ]
N = len (arr)
K = 4
NDivKWithFreq(arr, N, K)
|
C#
using System;
class GFG{
static void NDivKWithFreq( int [] arr, int N,
int K)
{
Array.Sort(arr);
for ( int i = 0; i < N;)
{
int cnt = 1;
while ((i + 1) < N &&
arr[i] == arr[i + 1])
{
cnt++;
i++;
}
if (cnt > (N / K))
{
Console.Write(arr[i] + " " );
}
i++;
}
}
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);
}
}
|
Javascript
<script>
function NDivKWithFreq(arr, N, K)
{
arr.sort();
for (let i = 0; i < N;) {
let cnt = 1;
while ((i + 1) < N
&& arr[i] == arr[i + 1]) {
cnt++;
i++;
}
if (cnt > (N / K)) {
document.write(arr[i]+ " " );
}
i++;
}
}
let arr = [1, 2, 2, 6, 6, 6, 6, 7, 10 ];
let N = arr.length;
let K = 4;
NDivKWithFreq(arr, N, K);
</script>
|
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++
#include <bits/stdc++.h>
using namespace std;
int upperBound( int arr[], int N, int K)
{
int l = 0;
int r = N;
while (l < r) {
int mid = (l + r) / 2;
if (arr[mid] <= K) {
l = mid + 1;
}
else {
r = mid;
}
}
return l;
}
void NDivKWithFreq( int arr[], int N, int K)
{
sort(arr, arr + N);
int i = 0;
while (i < N) {
int X = upperBound(arr, N, arr[i]);
if ((X - i) > N / 4) {
cout << arr[i] << " " ;
}
i = X;
}
}
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
import java.util.*;
class GFG{
static int upperBound( int arr[], int N, int K)
{
int l = 0 ;
int r = N;
while (l < r)
{
int mid = (l + r) / 2 ;
if (arr[mid] <= K)
{
l = mid + 1 ;
}
else
{
r = mid;
}
}
return l;
}
static void NDivKWithFreq( int arr[], int N, int K)
{
Arrays.sort(arr);
int i = 0 ;
while (i < N)
{
int X = upperBound(arr, N, arr[i]);
if ((X - i) > N / 4 )
{
System.out.print(arr[i] + " " );
}
i = X;
}
}
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);
}
}
|
Python3
def upperBound(arr, N, K):
l = 0 ;
r = N;
while (l < r):
mid = (l + r) / / 2 ;
if (arr[mid] < = K):
l = mid + 1 ;
else :
r = mid;
return l;
def NDivKWithFreq(arr, N, K):
arr.sort();
i = 0 ;
while (i < N):
X = upperBound(arr, N, arr[i]);
if ((X - i) > N / / 4 ):
print (arr[i], end = "");
i = X;
if __name__ = = '__main__' :
arr = [ 1 , 2 , 2 , 6 , 6 , 6 , 6 , 7 , 10 ];
N = len (arr);
K = 4 ;
NDivKWithFreq(arr, N, K);
|
Javascript
<script>
function 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 upperBound( arr, N, K)
{
var l = 0;
var r = N;
while (l < r) {
var mid = parseInt((l + r) / 2);
if (arr[mid] <= K) {
l = mid + 1;
}
else {
r = mid;
}
}
return l;
}
function NDivKWithFreq(arr, N, K)
{
sortt(arr);
var i = 0;
while (i < N) {
var X = upperBound(arr, N, arr[i]);
if ((X - i) > parseInt(N / 4)) {
document.write( arr[i] + " " );
}
i = X;
}
}
var arr = [ 1, 2, 2, 6, 6, 6, 6, 7, 10 ];
var N = arr.length;
var K = 4;
NDivKWithFreq(arr, N, K);
</script>
|
C#
using System;
class GFG
{
static int upperBound( int []arr, int N, int K)
{
int l = 0;
int r = N;
while (l < r)
{
int mid = (l + r) / 2;
if (arr[mid] <= K)
{
l = mid + 1;
}
else
{
r = mid;
}
}
return l;
}
static void NDivKWithFreq( int []arr, int N, int K)
{
Array.Sort(arr);
int i = 0;
while (i < N)
{
int X = upperBound(arr, N, arr[i]);
if ((X - i) > N / 4)
{
Console.Write(arr[i] + " " );
}
i = X;
}
}
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);
}
}
|
Time Complexity: O(N * log2N)
Auxiliary Space: O(1)
Another Approach: Using Built-in Python functions:
- 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:
C++
#include<bits/stdc++.h>
using namespace std;
void printELements(vector< int > arr, int n, int k){
int x = n/k;
map< int , int > mp;
for ( int i = 0; i < n; i++){
mp[arr[i]]++;
}
for ( auto it: mp){
if (it.second > x){
cout << it.first << endl;
}
}
}
int main(){
vector< int > arr = {1, 2, 2, 6, 6, 6, 6, 7, 10};
int n = arr.size();
int k = 4;
printELements(arr, n, k);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static void printELements( int [] arr, int n, int k)
{
int x = n/k;
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 );
}
for (Map.Entry<Integer,Integer> it : mp.entrySet()){
if (it.getValue() > x){
System.out.println(it.getKey());
}
}
}
public static void main (String[] args)
{
int [] arr = { 1 , 2 , 2 , 6 , 6 , 6 , 6 , 7 , 10 };
int n = arr.length;
int k = 4 ;
printELements(arr, n, k);
}
}
|
Python3
from collections import Counter
def printElements(arr, n, k):
x = n / / k
mp = Counter(arr)
for it in mp:
if mp[it] > x:
print (it)
arr = [ 1 , 2 , 2 , 6 , 6 , 6 , 6 , 7 , 10 ]
n = len (arr)
k = 4
printElements(arr, n, k)
|
Javascript
function printELements(arr, n, k)
{
let x = n/k;
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);
}
mp.forEach((values,keys)=>{
if (values > x){
document.write(keys);
}
})
}
let arr = [1, 2, 2, 6, 6, 6, 6, 7, 10];
let n = arr.length;
let k = 4;
printELements(arr, n, k);
|
C#
using System;
using System.Linq;
using System.Collections.Generic;
class GFG
{
static void printELements(List< int > arr, int n, int k)
{
int x = n/k;
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);
}
foreach (KeyValuePair< int , int > entry in mp)
{
if (entry.Value > x)
Console.Write(entry.Key);
}
}
static public void Main()
{
List< int > arr = new List< int >{1, 2, 2, 6, 6, 6, 6, 7, 10};
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:
- Create an empty hashmap freq_map to store the frequency of each element in the array.
- Traverse the array arr and insert each element of arr into freq_map, and increment its frequency by 1.
- Traverse the freq_map and for each key-value pair in the map, check if the value is greater than (N / K).
- If the value is greater than (N / K), then append the key to the list of required elements.
- Return the list of required elements.
C++
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
vector< int > find_elements(vector< int >& 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< int > req_elements;
for ( auto & p : freq_map) {
if (p.second > (N / K)) {
req_elements.push_back(p.first);
}
}
return req_elements;
}
int main()
{
vector< int > arr = { 1, 2, 6, 6, 6, 6, 6, 10 };
int K = 4;
vector< int > 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>();
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 );
}
}
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))
|
C#
using System;
using System.Collections.Generic;
class Program
{
static List< int > FindElements(List< int > 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< int > req_elements = new List< int >();
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...