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

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: 

\frac{(K*(\text{sum of unique element}) - (\text{sum of all element}))}{(K - 1)}



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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include <bits/stdc++.h>
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 Code
int main()
{
 
    int arr[] = { 12, 1, 12, 3, 12, 1,
                  1, 2, 3, 2, 2, 3, 7 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 3;
 
    // Function call
    findUniqueElements(arr, N, K);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import 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<Integer> 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 code
public 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 Code
if __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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
using System.Collections.Generic;
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
    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 code
public 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

chevron_right


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

Index Elements 2nd bit 1st bit 0th bit
0 2= 010 0 1 0
1 2= 010 0 1 0
2 4 =100 1 0 0
3 2= 010 0 1 0
4 2= 010 0 1 0
5 2= 010 0 1 0
6 1 = 001 0 0 1
7 1 = 001 0 0 1
8 1 = 001 0 0 1
9 1 = 001 0 0 1
10 1 = 001 0 0 1
Sum%k   1%5=1 5%5=0 5%5=0
Result   1 0 0

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find single occurance element
int 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 code
int 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

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.Arrays;
class Main{
     
// Function to find single
// occurance element
public 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 code
public 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the
// above approach
using System;
class GFG{
      
// Function to find single
// occurance element
public 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 code
public 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

chevron_right


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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.