Unique element in an array where all elements occur k times except one in C++


we have an array A. A has all elements occurring m times, but one element occurs only once. We have to find that unique 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

Let us see the following implementation to get better understanding −

Example (C++)

 Live Demo

#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

Updated on: 27-Aug-2020

265 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements