Given an array arr[] consisting of N integers and a positive integer M, the task is to find the number of array elements that occur at least M times.
Examples:
Input: arr[] = {2, 3, 2, 2, 3, 5, 6, 3}, M = 2
Output: 2 3
Explanation:
In the given array arr[], the element that occurs at least M number of times are {2, 3}.
Input: arr[] = {1, 32, 2, 1, 33, 5, 1, 5}, M = 2
Output: 1 5
Naive Approach: The simplest approach to solve the problem is as follows:
- Traverse the array from left to right
- Check if an element has already appeared in the earlier traversal or not. If appeared check for the next element. Else again traverse the array from ith position to (n – 1)th position.
- If the frequency is >= M. Print the element.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printElements( int arr[], int N, int M)
{
for ( int i = 0; i < N; i++) {
int j;
for (j = i - 1; j >= 0; j--) {
if (arr[i] == arr[j])
break ;
}
if (j >= 0)
continue ;
int freq = 0;
for (j = i; j < N; j++) {
if (arr[j] == arr[i])
freq++;
}
if (freq >= M)
cout << arr[i] << " " ;
}
}
int main()
{
int arr[] = { 2, 3, 2, 2, 3, 5, 6, 3 };
int M = 2;
int N = sizeof (arr) / sizeof (arr[0]);
printElements(arr, N, M);
return 0;
}
|
Java
import java.io.*;
class GFG{
static void printElements( int [] arr, int N, int M)
{
for ( int i = 0 ; i < N; i++)
{
int j;
for (j = i - 1 ; j >= 0 ; j--)
{
if (arr[i] == arr[j])
break ;
}
if (j >= 0 )
continue ;
int freq = 0 ;
for (j = i; j < N; j++)
{
if (arr[j] == arr[i])
freq++;
}
if (freq >= M)
System.out.print(arr[i] + " " );
}
}
public static void main(String[] args)
{
int [] arr = { 2 , 3 , 2 , 2 , 3 , 5 , 6 , 3 };
int M = 2 ;
int N = arr.length;
printElements(arr, N, M);
}
}
|
Python3
def printElements(arr, N, M):
for i in range (N):
j = i - 1
while j > = 0 :
if (arr[i] = = arr[j]):
break
j - = 1
if (j > = 0 ):
continue
freq = 0
for j in range (i, N):
if (arr[j] = = arr[i]):
freq + = 1
if (freq > = M):
print (arr[i], end = " " )
arr = [ 2 , 3 , 2 , 2 , 3 , 5 , 6 , 3 ]
M = 2
N = len (arr)
printElements(arr, N, M)
|
Javascript
<script>
function printElements(arr, N, M)
{
for (let i = 0; i < N; i++) {
let j;
for (j = i - 1; j >= 0; j--) {
if (arr[i] == arr[j])
break ;
}
if (j >= 0)
continue ;
let freq = 0;
for (j = i; j < N; j++) {
if (arr[j] == arr[i])
freq++;
}
if (freq >= M)
document.write(arr[i] + " " );
}
}
let arr = [ 2, 3, 2, 2, 3, 5, 6, 3 ];
let M = 2;
let N = arr.length;
printElements(arr, N, M);
</script>
|
C#
using System;
class GFG{
static void printElements( int [] arr, int N, int M)
{
for ( int i = 0; i < N; i++)
{
int j;
for (j = i - 1; j >= 0; j--)
{
if (arr[i] == arr[j])
break ;
}
if (j >= 0)
continue ;
int freq = 0;
for (j = i; j < N; j++)
{
if (arr[j] == arr[i])
freq++;
}
if (freq >= M)
Console.Write(arr[i] + " " );
}
}
public static void Main()
{
int [] arr = { 2, 3, 2, 2, 3, 5, 6, 3 };
int M = 2;
int N = arr.Length;
printElements(arr, N, M);
}
}
|
Approach: The given problem can be solved by storing the frequencies of array elements in a HashMap, say M, and print all the elements in the map having frequency at least M.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
void printElements( int arr[], int N, int M)
{
unordered_map< int , int > freq;
for ( int i = 0; i < N; i++) {
freq[arr[i]]++;
}
for ( auto it : freq) {
if (it.second >= M) {
cout << it.first << " " ;
}
}
return ;
}
int main()
{
int arr[] = { 2, 3, 2, 2,
3, 5, 6, 3 };
int M = 2;
int N = sizeof (arr) / sizeof (arr[0]);
printElements(arr, N, M);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG
{
static void printElements( int arr[], int N, int M)
{
HashMap<Integer, Integer> freq = new HashMap<>();
for ( int i = 0 ; i < N; i++)
{
freq.put(arr[i],
freq.getOrDefault(arr[i], 0 ) + 1 );
}
for ( int key : freq.keySet())
{
if (freq.get(key) >= M) {
System.out.print(key + " " );
}
}
}
public static void main(String[] args)
{
int arr[] = { 2 , 3 , 2 , 2 , 3 , 5 , 6 , 3 };
int M = 2 ;
int N = arr.length;
printElements(arr, N, M);
}
}
|
Python3
def printElements(arr, N, M):
freq = {}
for i in arr:
freq[i] = freq.get(i, 0 ) + 1
for it in freq:
if (freq[it] > = M):
print (it, end = " " )
return
if __name__ = = '__main__' :
arr = [ 2 , 3 , 2 , 2 , 3 , 5 , 6 , 3 ]
M = 2
N = len (arr)
printElements(arr, N, M)
|
Javascript
<script>
function printElements(arr, N, M) {
let freq = new Map();
for (let i = 0; i < N; i++) {
freq[arr[i]]++;
if (freq.has(arr[i])) {
freq.set(arr[i], freq.get(arr[i]) + 1)
} else {
freq.set(arr[i], 1)
}
}
for (let it of freq) {
if (it[1] >= M) {
document.write(it[0] + " " );
}
}
return ;
}
let arr = [2, 3, 2, 2,
3, 5, 6, 3];
let M = 2;
let N = arr.length;
printElements(arr, N, M);
</script>
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void printElements( int []arr, int N, int M)
{
Dictionary< int ,
int > freq = new Dictionary< int ,
int >();
for ( int i = 0; i < N; i++)
{
if (freq.ContainsKey(arr[i]))
freq[arr[i]] += 1;
else
freq[arr[i]] = 1;
}
foreach ( var item in freq)
{
if (item.Value >= M)
{
Console.Write(item.Key + " " );
}
}
return ;
}
public static void Main()
{
int []arr = { 2, 3, 2, 2,
3, 5, 6, 3 };
int M = 2;
int N = arr.Length;
printElements(arr, N, M);
}
}
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Method #2:Using Built in functions:
- Count the frequencies of every element using built-in function
- Traverse the frequency array and print all the elements which occur at least m times.
Below is the implementation:
C++
#include <iostream>
#include <map>
void printElements( int arr[], int M, int size)
{
std::map< int , int > mp;
for ( int i = 0; i < size; i++) {
if (mp.find(arr[i]) != mp.end()) {
mp[arr[i]]++;
}
else {
mp[arr[i]] = 1;
}
}
for ( auto entry : mp) {
if (entry.second >= M) {
std::cout << entry.first << " " ;
}
}
}
int main() {
int arr[] = { 2, 3, 2, 2, 3, 5, 6, 3 };
int M = 2;
printElements(arr, M, 8);
}
|
Java
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void printElements( int [] arr, int M)
{
Map<Integer, Integer> mp = new HashMap<>();
for ( int val : arr) {
if (mp.containsKey(val)) {
mp.put(val, mp.get(val) + 1 );
} else {
mp.put(val, 1 );
}
}
for (Map.Entry<Integer, Integer> entry : mp.entrySet()) {
if (entry.getValue() >= M) {
System.out.print(entry.getKey() + " " );
}
}
}
public static void main(String[] args) {
int [] arr = { 2 , 3 , 2 , 2 , 3 , 5 , 6 , 3 };
int M = 2 ;
printElements(arr, M);
}
}
|
Python3
from collections import Counter
def printElements(arr, M):
mp = Counter(arr)
for it in mp:
if mp[it] > = M:
print (it, end = " " )
arr = [ 2 , 3 , 2 , 2 , 3 , 5 , 6 , 3 ]
M = 2
printElements(arr, M)
|
Javascript
function printElements(arr, M)
{
const mp = new Map();
for (const val of arr) {
if (mp.has(val)) {
mp.set(val, mp.get(val) + 1);
} else {
mp.set(val, 1);
}
}
for (const [key, value] of mp) {
if (value >= M) {
console.log(key);
}
}
}
const arr = [2, 3, 2, 2, 3, 5, 6, 3];
const M = 2;
printElements(arr, M);
|
C#
using System;
using System.Collections.Generic;
public class Program
{
public static void PrintElements( int [] arr, int M)
{
Dictionary< int , int > dict = new Dictionary< int , int >();
foreach ( int val in arr)
{
if (dict.ContainsKey(val))
{
dict[val]++;
}
else
{
dict[val] = 1;
}
}
foreach (KeyValuePair< int , int > entry in dict)
{
if (entry.Value >= M)
{
Console.Write(entry.Key + " " );
}
}
}
public static void Main( string [] args)
{
int [] arr = { 2, 3, 2, 2, 3, 5, 6, 3 };
int M = 2;
PrintElements(arr, M);
}
}
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Approach:
One approach to solve this problem is to sort the array in non-decreasing order, and then traverse through the sorted array to count the frequency of each element. After that, we can traverse through the frequency array to find the elements that occur at least M times.
Steps:
- Sort the array in non-decreasing order.
- Initialize a variable ‘count’ to keep track of the number of elements that occur at least M times.
- Initialize two variables, ‘currElement’ and ‘currFrequency’ to keep track of the current element and its frequency while traversing through the sorted array.
- Traverse through the sorted array and count the frequency of each element. If the current element is different from the previous element, reset the ‘currFrequency’ to 1.
- Traverse through the frequency array to find the elements that occur at least M times. If the frequency of an element is greater than or equal to M, print the element.
C++
#include <iostream>
#include <algorithm>
using namespace std;
void PrintElements( int arr[], int n, int M);
int main() {
int arr[] = { 2, 3, 2, 2, 3, 5, 6, 3 };
int M = 2;
int n = sizeof (arr) / sizeof (arr[0]);
PrintElements(arr, n, M);
return 0;
}
void PrintElements( int arr[], int n, int M) {
sort(arr, arr + n);
int count = 0;
int currElement = arr[0];
int currFrequency = 1;
for ( int i = 1; i < n; i++) {
if (arr[i] == currElement) {
currFrequency++;
}
else {
if (currFrequency >= M) {
cout << currElement << " " ;
count++;
}
currElement = arr[i];
currFrequency = 1;
}
}
if (currFrequency >= M) {
cout << currElement << " " ;
count++;
}
cout << "\nNumber of elements occurring at least " << M << " times: " << count << endl;
}
|
Java
import java.util.*;
public class Main {
public static void printElements( int [] arr, int M) {
int n = arr.length;
Arrays.sort(arr);
int count = 0 ;
int currElement = arr[ 0 ];
int currFrequency = 1 ;
for ( int i = 1 ; i < n; i++) {
if (arr[i] == currElement) {
currFrequency++;
} else {
if (currFrequency >= M) {
System.out.print(currElement + " " );
count++;
}
currElement = arr[i];
currFrequency = 1 ;
}
}
if (currFrequency >= M) {
System.out.print(currElement + " " );
count++;
}
System.out.println( "\nNumber of elements occurring at least " + M + " times: " + count);
}
public static void main(String[] args) {
int [] arr = { 2 , 3 , 2 , 2 , 3 , 5 , 6 , 3 };
int M = 2 ;
printElements(arr, M);
}
}
|
Python3
def printElements(arr, M):
n = len (arr)
arr.sort()
count = 0
currElement = arr[ 0 ]
currFrequency = 1
for i in range ( 1 , n):
if arr[i] = = currElement:
currFrequency + = 1
else :
if currFrequency > = M:
print (currElement, end = " " )
count + = 1
currElement = arr[i]
currFrequency = 1
if currFrequency > = M:
print (currElement, end = " " )
count + = 1
print ( "\nNumber of elements occurring at least {} times: {}" . format (M, count))
arr = [ 2 , 3 , 2 , 2 , 3 , 5 , 6 , 3 ]
M = 2
printElements(arr, M)
|
C#
using System;
using System.Linq;
class Program {
static void Main( string [] args) {
int [] arr = new int [] { 2, 3, 2, 2, 3, 5, 6, 3 };
int M = 2;
PrintElements(arr, M);
}
static void PrintElements( int [] arr, int M) {
int n = arr.Length;
Array.Sort(arr);
int count = 0;
int currElement = arr[0];
int currFrequency = 1;
for ( int i = 1; i < n; i++) {
if (arr[i] == currElement) {
currFrequency++;
}
else {
if (currFrequency >= M) {
Console.Write(currElement + " " );
count++;
}
currElement = arr[i];
currFrequency = 1;
}
}
if (currFrequency >= M) {
Console.Write(currElement + " " );
count++;
}
Console.WriteLine($ "\nNumber of elements occurring at least {M} times: {count}" );
}
}
|
Javascript
function printElements(arr, M) {
let n = arr.length;
arr.sort((a, b) => a - b);
let count = 0;
let currElement = arr[0];
let currFrequency = 1;
let result = [];
for (let i = 1; i < n; i++) {
if (arr[i] == currElement) {
currFrequency++;
} else {
if (currFrequency >= M) {
result.push(currElement);
count++;
}
currElement = arr[i];
currFrequency = 1;
}
}
if (currFrequency >= M) {
result.push(currElement);
count++;
}
console.log(`Elements occurring at least ${M} times: ${result.join( ' ' )}`);
console.log(`Number of elements occurring at least ${M} times: ${count}`);
}
let arr = [2, 3, 2, 2, 3, 5, 6, 3];
let M = 2;
printElements(arr, M);
|
Output
2 3
Number of elements occurring at least 2 times: 2
Time complexity: O(nlogn)
Auxiliary space: O(1)
Please Login to comment...