Unique element in an array where all elements occur k times except one
Last Updated :
07 Nov, 2023
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.
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.
- Create an array count[] of size equal to number of bits in binary representations of numbers.
- Fill count array such that count[i] stores count of array elements with i-th bit set.
- 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++
#include <bits/stdc++.h>
using namespace std;
int findUnique(unsigned int a[], int n, int k)
{
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 < n; j++)
if ((a[j] & (1 << i)) != 0)
count[i] += 1;
unsigned res = 0;
for ( int i = 0; i < INT_SIZE; i++)
res += (count[i] % k) * (1 << i);
res = res / (n % k);
return res;
}
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
class GFG {
static int findUnique( int a[], int n, int k)
{
byte sizeof_int = 4 ;
int INT_SIZE = 8 * sizeof_int;
int count[] = new int [INT_SIZE];
for ( int i = 0 ; i < INT_SIZE; i++)
for ( int j = 0 ; j < n; j++)
if ((a[j] & ( 1 << i)) != 0 )
count[i] += 1 ;
int res = 0 ;
for ( int i = 0 ; i < INT_SIZE; i++)
res += (count[i] % k) * ( 1 << i);
res = res / (n % k);
return res;
}
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));
}
}
|
Python3
import sys
def findUnique(a, n, k):
INT_SIZE = 8 * sys.getsizeof( int )
count = [ 0 ] * INT_SIZE
for i in range (INT_SIZE):
for j in range (n):
if ((a[j] & ( 1 << i)) ! = 0 ):
count[i] + = 1
res = 0
for i in range (INT_SIZE):
res + = (count[i] % k) * ( 1 << i)
res = res / (n % k)
return res
if __name__ = = '__main__' :
a = [ 6 , 2 , 5 , 2 , 2 , 6 , 6 ]
n = len (a)
k = 3
print (findUnique(a, n, k))
|
C#
using System;
class GFG {
static int findUnique( int [] a, int n, int k)
{
byte sizeof_int = 4;
int INT_SIZE = 8 * sizeof_int;
int [] count = new int [INT_SIZE];
for ( int i = 0; i < INT_SIZE; i++)
for ( int j = 0; j < n; j++)
if ((a[j] & (1 << i)) != 0)
count[i] += 1;
int res = 0;
for ( int i = 0; i < INT_SIZE; i++)
res += (count[i] % k) * (1 << i);
res = res / (n % k);
return res;
}
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));
}
}
|
Javascript
<script>
function findUnique(a, n, k)
{
let sizeof_let = 4;
let LET_SIZE = 8 * sizeof_let;
let count = Array.from({length: LET_SIZE}, (_, i) => 0);
for (let i = 0; i < LET_SIZE; i++)
for (let j = 0; j < n; j++)
if ((a[j] & (1 << i)) != 0)
count[i] += 1;
let res = 0;
for (let i = 0; i < LET_SIZE; i++)
res += (count[i] % k) * (1 << i);
res = res / (n % k);
return res;
}
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
function findUnique( $a , $n , $k )
{
$INT_SIZE = 8 * PHP_INT_SIZE;
$count = array ();
for ( $i =0; $i < $INT_SIZE ; $i ++)
$count [ $i ] = 0;
for ( $i = 0; $i < $INT_SIZE ; $i ++)
for ( $j = 0; $j < $n ; $j ++)
if (( $a [ $j ] & (1 << $i )) != 0)
$count [ $i ] += 1;
$res = 0;
for ( $i = 0; $i < $INT_SIZE ; $i ++)
$res += ( $count [ $i ] % $k ) * (1 << $i );
$res = $res / ( $n % $k );
return $res ;
}
$a = array ( 6, 2, 5, 2, 2, 6, 6 );
$n = count ( $a );
$k = 3;
echo findUnique( $a , $n , $k );
?>
|
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;
int findUniqueElement( int arr[], int n, int k) {
unordered_map< int , int > freqMap;
for ( int i = 0; i < n; i++) {
int num = arr[i];
freqMap[num]++;
}
for ( const auto & entry : freqMap) {
if (entry.second != k) {
return entry.first;
}
}
return -1;
}
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 ;
}
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
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
{
static int FindUniqueElement( int [] arr, int k)
{
Dictionary< int , int > freqMap = new Dictionary< int , int >();
foreach ( int num in arr)
{
if (freqMap.ContainsKey(num))
{
freqMap[num]++;
}
else
{
freqMap[num] = 1;
}
}
foreach ( var entry in freqMap)
{
if (entry.Value != k)
{
return entry.Key;
}
}
return -1;
}
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 findUniqueElement(arr, k) {
let freqMap = new Map();
for (let i = 0; i < arr.length; i++) {
let num = arr[i];
if (freqMap.has(num)) {
freqMap.set(num, freqMap.get(num) + 1);
} else {
freqMap.set(num, 1);
}
}
for (const [key, value] of freqMap) {
if (value !== k) {
return key;
}
}
return -1;
}
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." );
}
|
Time Complexity: O(n)
Space Complexity: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...