Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Find the element having different frequency than other array elements in C++
Suppose we have an array of N numbers, where each element in the array appears same number of times (m times, this is also given) except one element, We have to find this element.
So, if the input is like A = [6, 2, 7, 2, 2, 6, 6], m = 3, then the output will be 7.
To solve this, we will follow these steps −
INT_SIZE := 8 * size of an integer type variable
Define an array count of size − INT_SIZE. and fill with 0
-
for initialize i := 0, when i < INT_SIZE, update (increase i by 1), do:
-
for initialize j := 0, when j < size, update (increase j by 1), do −
-
if (arr[j] AND 2^i) is not equal to 0, then −
count[i] := count[i] + 1
res := 0
-
-
for initialize i := 0, when i < INT_SIZE, update (increase i by 1), do −
res := res + ((count[i] mod m) * 2^i)
return res
-
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h>
using namespace std;
int selectUnique(unsigned int arr[], int size, int m){
int INT_SIZE = 8 * sizeof(unsigned int);
int count[INT_SIZE];
memset(count, 0, sizeof(count));
for(int i = 0; i < INT_SIZE; i++)
for(int j = 0; j < size; j++)
if((arr[j] & (1 << i)) != 0)
count[i] += 1;
unsigned res = 0;
for(int i = 0; i < INT_SIZE; i++)
res += (count[i] % m) * (1 << i);
return res;
}
main(){
unsigned int arr[] = { 6, 2, 5, 2, 2, 6, 6 };
int size = sizeof(arr) / sizeof(arr[0]);
int m = 3;
cout << selectUnique(arr, size, m);
}
Input
{ 6, 2, 5, 2, 2, 6, 6 }
Output
5
