Skip to content
Related Articles

Related Articles

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

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 19 Jul, 2022
Improve Article
Save Article

Given an array that contains all elements occurring k times, but one occurs only once. Find that unique element.
Examples: 

Input  : arr[] = {6, 2, 5, 2, 2, 6, 6}
            k = 3
Output : 5
Explanation: Every element appears 3 times accept 5.

Input  : arr[] = {2, 2, 2, 10, 2}
            k = 4
Output: 10
Explanation: Every element appears 4 times accept 10.
 

Recommended Practice

A Simple Solution is to use two nested loops. The outer loop picks an element one by one starting from the leftmost element. The inner loop checks if the element is present k times or not. If present, then ignores the element, else prints the element. 

The Time Complexity of the above solution is O(n2). We can Use Sorting to solve the problem in O(nLogn) time. The idea is simple, the first sort the array so that all occurrences of every element become consecutive. Once the occurrences become consecutive, we can traverse the sorted array and print the unique element in O(n) time.
We can Use Hashing to solve this in O(n) time on average. The idea is to traverse the given array from left to right and keep track of visited elements in a hash table. Finally, print the element with count 1.

The hashing-based solution requires O(n) extra space. We can use bitwise AND to find the unique element in O(n) time and constant extra space. 

  1. Create an array count[] of size equal to number of bits in binary representations of numbers.
  2. Fill count array such that count[i] stores count of array elements with i-th bit set.
    1. Form result using count array. We put 1 at a position i in result if count[i] is not multiple of k. Else we put 0.

Below is the implementation of the above approach:

C++




// CPP program to find unique element where
// every element appears k times except one
#include <bits/stdc++.h>
using namespace std;
 
int findUnique(unsigned int a[], int n, int k)
{
    // Create a count array to store count of
    // numbers that have a particular bit set.
    // count[i] stores count of array elements
    // with i-th bit set.
    int INT_SIZE = 8 * sizeof(unsigned int);
    int count[INT_SIZE];
    memset(count, 0, sizeof(count));
 
    // AND(bitwise) each element of the array
    // with each set digit (one at a time)
    // to get the count of set bits at each
    // position
    for (int i = 0; i < INT_SIZE; i++)
        for (int j = 0; j < n; j++)
            if ((a[j] & (1 << i)) != 0)
                count[i] += 1;
 
    // Now consider all bits whose count is
    // not multiple of k to form the required
    // number.
    unsigned res = 0;
    for (int i = 0; i < INT_SIZE; i++)
        res += (count[i] % k) * (1 << i);
 
    // Before returning the res we need
    // to check the occurrence  of that
    // unique element and divide it
    res = res / (n % k);
    return res;
}
 
// Driver Code
int main()
{
    unsigned int a[] = { 6, 2, 5, 2, 2, 6, 6 };
    int n = sizeof(a) / sizeof(a[0]);
    int k = 3;
    cout << findUnique(a, n, k);
    return 0;
}

Java




// Java program to find unique element where
// every element appears k times except one
 
class GFG {
 
    static int findUnique(int a[], int n, int k)
    {
        // Create a count array to store count of
        // numbers that have a particular bit set.
        // count[i] stores count of array elements
        // with i-th bit set.
        byte sizeof_int = 4;
        int INT_SIZE = 8 * sizeof_int;
        int count[] = new int[INT_SIZE];
 
        // AND(bitwise) each element of the array
        // with each set digit (one at a time)
        // to get the count of set bits at each
        // position
        for (int i = 0; i < INT_SIZE; i++)
            for (int j = 0; j < n; j++)
                if ((a[j] & (1 << i)) != 0)
                    count[i] += 1;
 
        // Now consider all bits whose count is
        // not multiple of k to form the required
        // number.
        int res = 0;
        for (int i = 0; i < INT_SIZE; i++)
            res += (count[i] % k) * (1 << i);
 
        // Before returning the res we need
        // to check the occurrence  of that
        // unique element and divide it
        res = res / (n % k);
 
        return res;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int a[] = { 6, 2, 5, 2, 2, 6, 6 };
        int n = a.length;
        int k = 3;
        System.out.println(findUnique(a, n, k));
    }
}
 
// This code is contributed by 29AjayKumar

Python3




# Python 3 program to find unique element where
# every element appears k times except one
import sys
 
 
def findUnique(a, n, k):
 
    # Create a count array to store count of
    # numbers that have a particular bit set.
    # count[i] stores count of array elements
    # with i-th bit set.
    INT_SIZE = 8 * sys.getsizeof(int)
    count = [0] * INT_SIZE
 
    # AND(bitwise) each element of the array
    # with each set digit (one at a time)
    # to get the count of set bits at each
    # position
    for i in range(INT_SIZE):
        for j in range(n):
            if ((a[j] & (1 << i)) != 0):
                count[i] += 1
 
    # Now consider all bits whose count is
    # not multiple of k to form the required
    # number.
    res = 0
    for i in range(INT_SIZE):
        res += (count[i] % k) * (1 << i)
 
    # Before returning the res we need
    # to check the occurrence  of that
    # unique element and divide it
    res = res / (n % k)
    return res
 
 
# Driver Code
if __name__ == '__main__':
    a = [6, 2, 5, 2, 2, 6, 6]
    n = len(a)
    k = 3
    print(findUnique(a, n, k))
 
# This code is contributed by
# Surendra_Gangwar

C#




// C# program to find unique element where
// every element appears k times except one
using System;
 
class GFG {
    static int findUnique(int[] a, int n, int k)
    {
        // Create a count array to store count of
        // numbers that have a particular bit set.
        // count[i] stores count of array elements
        // with i-th bit set.
        byte sizeof_int = 4;
        int INT_SIZE = 8 * sizeof_int;
        int[] count = new int[INT_SIZE];
 
        // AND(bitwise) each element of the array
        // with each set digit (one at a time)
        // to get the count of set bits at each
        // position
        for (int i = 0; i < INT_SIZE; i++)
            for (int j = 0; j < n; j++)
                if ((a[j] & (1 << i)) != 0)
                    count[i] += 1;
 
        // Now consider all bits whose count is
        // not multiple of k to form the required
        // number.
        int res = 0;
        for (int i = 0; i < INT_SIZE; i++)
            res += (count[i] % k) * (1 << i);
 
        // Before returning the res we need
        // to check the occurrence  of that
        // unique element and divide it
        res = res / (n % k);
        return res;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] a = { 6, 2, 5, 2, 2, 6, 6 };
        int n = a.Length;
        int k = 3;
        Console.WriteLine(findUnique(a, n, k));
    }
}
 
// This code is contributed by PrinciRaj1992

PHP




<?php
//PHP program to find unique element where
// every element appears k times except one
 
 
function findUnique($a, $n, $k)
{
    // Create a count array to store count of
    // numbers that have a particular bit set.
    // count[i] stores count of array elements
    // with i-th bit set.
    $INT_SIZE = 8 * PHP_INT_SIZE;
    $count = array();
     
    for($i=0; $i< $INT_SIZE; $i++)
    $count[$i] = 0;
    // AND(bitwise) each element of the array
    // with each set digit (one at a time)
    // to get the count of set bits at each
    // position
    for ( $i = 0; $i < $INT_SIZE; $i++)
        for ( $j = 0; $j < $n; $j++)
            if (($a[$j] & (1 << $i)) != 0)
                $count[$i] += 1;
 
    // Now consider all bits whose count is
    // not multiple of k to form the required
    // number.
    $res = 0;
    for ($i = 0; $i < $INT_SIZE; $i++)
        $res += ($count[$i] % $k) * (1 << $i);
   
     // Before returning the res we need
    // to check the occurrence  of that
    // unique element and divide it
    $res = $res / ($n % $k);
    return $res;
}
 
    // Driver Code
    $a = array( 6, 2, 5, 2, 2, 6, 6 );
    $n = count($a);
    $k = 3;
    echo findUnique($a, $n, $k);
     
// This code is contributed by Rajput-Ji
?>

Javascript




<script>
// Javascript program to find unique element where
// every element appears k times except one
 
   function findUnique(a, n, k)
{
    // Create a count array to store count of
    // numbers that have a particular bit set.
    // count[i] stores count of array elements
    // with i-th bit set.
    let sizeof_let = 4;
    let LET_SIZE = 8 * sizeof_let;
    let count = Array.from({length: LET_SIZE}, (_, i) => 0); 
   
    // AND(bitwise) each element of the array
    // with each set digit (one at a time)
    // to get the count of set bits at each
    // position
    for (let i = 0; i < LET_SIZE; i++)
        for (let j = 0; j < n; j++)
            if ((a[j] & (1 << i)) != 0)
                count[i] += 1;
   
    // Now consider all bits whose count is
    // not multiple of k to form the required
    // number.
    let res = 0;
    for (let i = 0; i < LET_SIZE; i++)
        res += (count[i] % k) * (1 << i);
         
     // Before returning the res we need
    // to check the occurrence  of that
    // unique element and divide it
     
    res = res / (n % k);
    return res;
}
 
// driver function
 
    let a = [ 6, 2, 5, 2, 2, 6, 6 ];
    let n = a.length;
    let k = 3;
    document.write(findUnique(a, n, k));
   
</script>

Output

5

Time Complexity: O(n)
Auxiliary Space: O(1)

This article is contributed by Dhiman Mayank. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!