Open In App

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

Last Updated : 07 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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


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>


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


Output

5



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

This article is contributed by Dhiman Mayank.  

Using Set:

Approach:

In this approach, we create two sets: one to store the unique elements in the array, and the other to store the elements that appear k times. Then we return the difference between these two sets.

  • Create two empty sets: unique_set and k_set.
  • Iterate through each element in the array arr.
  • If the element is already in the unique_set, it means it has appeared before. Add it to k_set.
  • If the element is not in the unique_set, add it to unique_set.
  • Take the set difference between unique_set and k_set using the – operator. This gives us a set with only the unique element in it.
  • Use the pop() method to get the element from the set (since there is only one element in it).

C++




#include <iostream>
#include <vector>
#include <unordered_map>
 
using namespace std;
 
// Function to find a unique element with a specified frequency (k)
int findUniqueElement(int arr[], int n, int k) {
    unordered_map<int, int> freqMap; // Create an unordered_map to store frequency
 
    // Populate the frequency map
    for (int i = 0; i < n; i++) {
        int num = arr[i];
        freqMap[num]++; // Increment the frequency of the current element
    }
 
    // Iterate through the frequency map
    for (const auto& entry : freqMap) {
        if (entry.second != k) { // If the frequency is not equal to k
            return entry.first; // Return the unique element
        }
    }
 
    return -1; // Return -1 if no unique element is found
}
 
int main() {
    int arr[] = {6, 2, 5, 2, 2, 6, 6};
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
 
    int uniqueElement = findUniqueElement(arr, n, k);
 
    if (uniqueElement != -1) {
        cout << "Unique element: " << uniqueElement << endl;
    } else {
        cout << "No unique element found." << endl;
    }
 
    return 0;
}


Java




import java.util.HashMap;
import java.util.Map;
 
public class Main {
    public static int findUniqueElement(int[] arr, int k) {
        Map<Integer, Integer> freqMap = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            int num = arr[i];
            freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
        }
        for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {
            if (entry.getValue() != k) {
                return entry.getKey();
            }
        }
        return -1; // or any suitable default value to indicate no unique element found
    }
 
    public static void main(String[] args) {
        int[] arr = {6, 2, 5, 2, 2, 6, 6};
        int k = 3;
        int uniqueElement = findUniqueElement(arr, k);
        if (uniqueElement != -1) {
            System.out.println("Unique element: " + uniqueElement);
        } else {
            System.out.println("No unique element found.");
        }
    }
}


Python3




from collections import Counter
 
def find_unique_element(arr, k):
    freq_dict = Counter(arr)
    for key, val in freq_dict.items():
        if val != k:
            return key
 
# example usage
arr = [6, 2, 5, 2, 2, 6, 6]
k = 3
print(find_unique_element(arr, k))


C#




using System;
using System.Collections.Generic;
 
class Program
{
    // Function to find a unique element with a specified frequency (k)
    static int FindUniqueElement(int[] arr, int k)
    {
        Dictionary<int, int> freqMap = new Dictionary<int, int>(); // Create a Dictionary to store frequency
 
        // Populate the frequency map
        foreach (int num in arr)
        {
            if (freqMap.ContainsKey(num))
            {
                freqMap[num]++; // Increment the frequency of the current element
            }
            else
            {
                freqMap[num] = 1; // Initialize the frequency of the current element
            }
        }
 
        // Iterate through the frequency map
        foreach (var entry in freqMap)
        {
            if (entry.Value != k) // If the frequency is not equal to k
            {
                return entry.Key; // Return the unique element
            }
        }
 
        return -1; // Return -1 if no unique element is found
    }
 
    static void Main()
    {
        int[] arr = { 6, 2, 5, 2, 2, 6, 6 };
        int k = 3;
 
        int uniqueElement = FindUniqueElement(arr, k);
 
        if (uniqueElement != -1)
        {
            Console.WriteLine("Unique element: " + uniqueElement);
        }
        else
        {
            Console.WriteLine("No unique element found.");
        }
    }
}


Javascript




// Function to find a unique element with a specified frequency (k)
function findUniqueElement(arr, k) {
    let freqMap = new Map(); // Create a Map to store frequency
 
    // Populate the frequency map
    for (let i = 0; i < arr.length; i++) {
        let num = arr[i];
        if (freqMap.has(num)) {
            freqMap.set(num, freqMap.get(num) + 1); // Increment the frequency of the current element
        } else {
            freqMap.set(num, 1);
        }
    }
 
    // Iterate through the frequency map
    for (const [key, value] of freqMap) {
        if (value !== k) { // If the frequency is not equal to k
            return key; // Return the unique element
        }
    }
 
    return -1; // Return -1 if no unique element is found
}
 
const arr = [6, 2, 5, 2, 2, 6, 6];
const k = 3;
 
const uniqueElement = findUniqueElement(arr, k);
 
if (uniqueElement !== -1) {
    console.log("Unique element:", uniqueElement);
} else {
    console.log("No unique element found.");
}


Output

5



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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads