Related Articles

# Unique element in an array where all elements occur K times except one | Set 2

• Difficulty Level : Hard
• Last Updated : 02 Jun, 2021

Given an array arr[] where every element occurs K times except one element which occurs only once, the task is to find that unique element.
Examples:

Input: arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7}, k = 3
Output:
Explanation:
7 is the only element which occurs once while others occurs k times.
Input: arr[] = {12, 12, 2, 2, 3}, k = 2
Output:
Explanation:
3 is the only element which occurs once while others occurs k times.

Naive Approach: Suppose we have every element K times then the difference between the sum of all elements in the given array and the K*sum of all unique elements is (K-1) times the unique element.
For Example:

arr[] = {a, a, a, b, b, b, c, c, c, d}, k = 3
unique elements = {a, b, c, d}
Difference = 3*(a + b + c + d) – (a + a + a + b + b + b + c + c + c + d) = 2*d
Therefore, Generalizing the equation:
The unique element can be given by: Below are the steps:

1. Store all the elements of the given array in the set to get the unique elements.
2. Find the sum of all elements in the array (say sum_array) and the sum of all the elements in the set(say sum_set).
3. The unique element is given by (K*sum_set – sum_array)/(K – 1).

Below is the implementation of the above approach:

## C++

 // C++ program for the above approach #include using namespace std; // Function that find the unique element// in the array arr[]int findUniqueElements(int arr[], int N,                       int K){    // Store all unique element in set    unordered_set<int> s(arr, arr + N);     // Sum of all element of the array    int arr_sum = accumulate(arr, arr + N, 0);     // Sum of element in the set    int set_sum = accumulate(s.begin(),                             s.end(),                             0);     // Print the unique element using formula    cout << (K * set_sum - arr_sum) / (K - 1);} // Driver Codeint main(){     int arr[] = { 12, 1, 12, 3, 12, 1,                  1, 2, 3, 2, 2, 3, 7 };    int N = sizeof(arr) / sizeof(arr);    int K = 3;     // Function call    findUniqueElements(arr, N, K);     return 0;}

## Java

 // Java program for the above approachimport java.util.*; class GFG{     // Function that find the unique element// in the array arr[]static void findUniqueElements(int arr[],                               int N, int K){         // Store all unique element in set    Set s = new HashSet<>();    for(int i = 0; i < N; i++)        s.add(arr[i]);     // Sum of all element of the array    int arr_sum = 0;    for(int i = 0; i < N; i++)        arr_sum += arr[i];     // Sum of element in the set    int set_sum = 0;    Iterator it = s.iterator();     while (it.hasNext())    {        set_sum += (int)it.next();    }     // Print the unique element using formula    System.out.println((K * set_sum - arr_sum) /                       (K - 1));} // Driver codepublic static void main(String[] args){    int arr[] = { 12, 1, 12, 3, 12, 1,                  1, 2, 3, 2, 2, 3, 7 };    int N = arr.length;    int K = 3;     // Function call    findUniqueElements(arr, N, K);}} // This code is contributed by offbeat

## Python3

 # Python3 program for the above approach # Function that find the unique element# in the array arr[]def findUniqueElements(arr, N, K):         # Store all unique element in set    s = set()    for x in arr:        s.add(x)     # Sum of all element of the array    arr_sum = sum(arr)     # Sum of element in the set    set_sum = 0    for x in s:        set_sum += x     # Print the unique element using formula    print((K * set_sum - arr_sum) // (K - 1)) # Driver Codeif __name__ == '__main__':         arr = [ 12, 1, 12, 3, 12, 1,            1, 2, 3, 2, 2, 3, 7 ]    N = len(arr)    K = 3     # Function call    findUniqueElements(arr, N, K) # This code is contributed by Samarth

## C#

 // C# program for the above approachusing System;using System.Collections.Generic;class GFG{     // Function that find the unique element// in the array []arrstatic void findUniqueElements(int []arr,                               int N, int K){         // Store all unique element in set    HashSet<int> s = new HashSet<int>();    for(int i = 0; i < N; i++)        s.Add(arr[i]);     // Sum of all element of the array    int arr_sum = 0;    for(int i = 0; i < N; i++)        arr_sum += arr[i];     // Sum of element in the set    int set_sum = 0;    foreach(int i in s)        set_sum += i;      // Print the unique element using formula    Console.WriteLine((K * set_sum - arr_sum) /                      (K - 1));} // Driver codepublic static void Main(String[] args){    int []arr = { 12, 1, 12, 3, 12, 1,                  1, 2, 3, 2, 2, 3, 7 };    int N = arr.Length;    int K = 3;     // Function call    findUniqueElements(arr, N, K);}} // This code is contributed by gauravrajput1

## Javascript

 
Output
7

Time Complexity: O(N), where N is the number of elements in the array
Auxiliary Space Complexity: O(N/K), where K is the frequency.

Another Approach:  The idea is to use hashing but it will take O(n) time and requires extra space. We can also do it by sorting but it will take O(N log N) time.

Efficient Approach: The above problem can be optimized in terms of constant space complexity. Use bit manipulation approach for this problem.

• Let’s assume we have a case where all the elements appear k times except 1 element.
• So, count the bit of every element for 32 bits.
• Count 0th bit of every element and take modulo by k will eliminate the bit of elements which present k times and we remain with the only bit of element which presents one time.
• Apply this process for all the 32 bits and by taking modulo by k we will eliminate repeated elements bits.
• At every step, generate the results from these remaining bits.
• To handle any negative number, check if the result is present in the array or not if present then print it. Else print negative of the result.

For Example arr[] = {2, 2, 4, 2, 2, 2, 1, 1, 1, 1, 1} , k = 5

Our result is (100) in binary = 4 in decimal. So the final answer will be 4, because it presents 1 time.

Below is the implementation of the above approach:

## C++

 // CPP program for the above approach#include using namespace std; // Function to find single occurrence elementint findunique(vector<int>& a, int k){    int res = 0;     for (int i = 0; i < 32; i++) {        int p = 0;         for (int j = 0; j < a.size(); j++) {            // By shifting 1 to left ith            // time and taking and with 1            // will give us that ith            // bit of a[j] is 1 or 0            p += (abs(a[j]) & (                  1 << i)) != 0 ? 1 : 0;        }         // Taking modulo of p with k        p %= k;         // Generate result        res += pow(2, i) * p;    }     int c = 0;     // Loop for negative numbers    for (auto x : a)         if (x == res) {            c = 1;            break;        }       // Check if the calculated value res    // is present in array, then mark c=1    // and if c = 1 return res    // else res must be -ve    return c == 1 ? res : -res;} // Driver codeint main(){     vector<int> a = { 12, 12, 2, 2, 3 };    int k = 2;     // Function call    cout << findunique(a, k) << "\n";}// This article is contributed by ajaykr00kj

## Java

 // Java program for the above approachimport java.util.Arrays;class Main{     // Function to find single// occurrence elementpublic static int findunique(int a[],                             int k){  int res = 0;   for (int i = 0; i < 32; i++)  {    int p = 0;     for (int j = 0; j < a.length; j++)    {      // By shifting 1 to left ith      // time and taking and with 1      // will give us that ith      // bit of a[j] is 1 or 0      p += (Math.abs(a[j]) &           (1 << i)) != 0 ? 1 : 0;    }     // Taking modulo of p with k    p %= k;     // Generate result    res += Math.pow(2, i) * p;  }   int c = 0;   // Loop for negative numbers  for (int x = 0; x < a.length; x++)     if (a[x] == res)    {      c = 1;      break;    }   // Check if the calculated value res  // is present in array, then mark c=1  // and if c = 1 return res  // else res must be -ve  return c == 1 ? res : -res;} // Driver codepublic static void main(String[] args){  int a[] = {12, 12, 2, 2, 3};  int k = 2;   // Function call  System.out.println(findunique(a, k));}} // This code is contributed by divyeshrabadiya07

## Python3

 # Python3 program for the above approach # Function to find single occurrence elementdef findunique(a, k):     res = 0     for i in range(32):        p = 0         for j in range(len(a)):                       # By shifting 1 to left ith            # time and taking and with 1            # will give us that ith            # bit of a[j] is 1 or 0            if (abs(a[j]) & (1 << i)) != 0 :                p += 1         # Taking modulo of p with k        p %= k         # Generate result        res += pow(2, i) * p     c = 0     # Loop for negative numbers    for x in a:         if (x == res) :            c = 1            break     # Check if the calculated value res    # is present in array, then mark c=1    # and if c = 1 return res    # else res must be -ve    if c == 1 :        return res    else :        return -res # Driver codea = [ 12, 12, 2, 2, 3 ]k = 2 # Function callprint(findunique(a, k)) # This code is contributed by divyesh072019

## C#

 // C# program for the// above approachusing System;class GFG{      // Function to find single// occurrence elementpublic static int findunique(int []a,                             int k){  int res = 0;    for (int i = 0; i < 32; i++)  {    int p = 0;      for (int j = 0; j < a.Length; j++)    {      // By shifting 1 to left ith      // time and taking and with 1      // will give us that ith      // bit of a[j] is 1 or 0      p += (Math.Abs(a[j]) &           (1 << i)) != 0 ? 1 : 0;    }      // Taking modulo of p with k    p %= k;      // Generate result    res += (int)Math.Pow(2, i) * p;  }    int c = 0;    // Loop for negative numbers  for (int x = 0; x < a.Length; x++)      if (a[x] == res)    {      c = 1;      break;    }    // Check if the calculated value res  // is present in array, then mark c=1  // and if c = 1 return res  // else res must be -ve  return c == 1 ? res : -res;}  // Driver codepublic static void Main(string []args){  int []a = {12, 12, 2, 2, 3};  int k = 2;    // Function call  Console.Write(findunique(a, k));}} // This code is contributed by Rutvik_56

## Javascript

 

Output
3

Time Complexity: O(32 * n) = O(n)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up