Delete all odd frequency elements from an Array
Given an array arr containing integers of size N, the task is to delete all the elements from the array that have odd frequencies.
Examples:
Input: arr[] = {3, 3, 3, 2, 2, 4, 7, 7}
Output: {2, 2, 7, 7}
Explanation:
Frequency of 3 = 3
Frequency of 2 = 2
Frequency of 4 = 1
Frequency of 7 = 2
Therefore, the elements 3 and 4 have odd frequencies, and hence they are removed.
Input: arr[] = {1, 3, 3, 1, 2, 5, 6, 5}
Output: {1, 3, 3, 1, 5, 5}
Approach:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void remove ( int arr[], int n)
{
unordered_map< int , int > m;
for ( int i = 0; i < n; i++) {
m[arr[i]]++;
}
for ( int i = 0; i < n; i++) {
if ((m[arr[i]] & 1))
continue ;
cout << arr[i] << ", " ;
}
}
int main()
{
int arr[]
= { 3, 3, 3, 2,
2, 4, 7, 7 };
int n = sizeof (arr) / sizeof (arr[0]);
remove (arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void remove( int arr[], int n) {
HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>();
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 ( int i = 0 ; i < n; i++) {
if ((mp.containsKey(arr[i]) && mp.get(arr[i]) % 2 == 1 ))
continue ;
System.out.print(arr[i] + ", " );
}
}
public static void main(String[] args) {
int arr[] = { 3 , 3 , 3 , 2 , 2 , 4 , 7 , 7 };
int n = arr.length;
remove(arr, n);
}
}
|
Python3
def remove(arr, n) :
m = dict .fromkeys(arr, 0 );
for i in range (n) :
m[arr[i]] + = 1 ;
for i in range (n) :
if ((m[arr[i]] & 1 )) :
continue ;
print (arr[i],end = ", " );
if __name__ = = "__main__" :
arr = [ 3 , 3 , 3 , 2 ,
2 , 4 , 7 , 7 ];
n = len (arr);
remove(arr, n);
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void remove( int []arr, int n) {
Dictionary< int , int > mp = new Dictionary< int , int >();
for ( int i = 0; i < n; i++) {
if (mp.ContainsKey(arr[i])) {
mp[arr[i]] = mp[arr[i]] + 1;
} else {
mp.Add(arr[i], 1);
}
}
for ( int i = 0; i < n; i++) {
if ((mp.ContainsKey(arr[i]) && mp[arr[i]] % 2 == 1))
continue ;
Console.Write(arr[i] + ", " );
}
}
public static void Main(String[] args) {
int []arr = { 3, 3, 3, 2, 2, 4, 7, 7 };
int n = arr.Length;
remove(arr, n);
}
}
|
Javascript
<script>
function remove(arr, n) {
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);
}
}
for (let i = 0; i < n; i++) {
if ((mp.has(arr[i]) && mp.get(arr[i]) % 2 == 1))
continue ;
document.write(arr[i] + ", " );
}
}
let arr = [ 3, 3, 3, 2, 2, 4, 7, 7 ];
let n = arr.length;
remove(arr, n);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
15 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...