Given an array where every element occurs three times, except one element which occurs only once. Find the element that occurs once. The expected time complexity is O(n) and O(1) extra space.
Examples:
Input: arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 3}
Output: 2
In the given array all element appear three times except 2 which appears once.
Input: arr[] = {10, 20, 10, 30, 10, 30, 30}
Output: 20
In the given array all element appear three times except 20 which appears once.
We can use sorting to do it in O(nLogn) time. We can also use hashing, it has the worst-case time complexity of O(n), but requires extra space.
The idea is to use bitwise operators for a solution that is O(n) time and uses O(1) extra space. The solution is not easy like other XOR-based solutions, because all elements appear an odd number of times here. The idea is taken from here.
Run a loop for all elements in the array. At the end of every iteration, maintain the following two values.
ones: The bits that have appeared 1st time or 4th time or 7th time .. etc.
twos: The bits that have appeared 2nd time or 5th time or 8th time .. etc.
Finally, we return the value of ‘ones’
How to maintain the values of ‘ones’ and ‘twos’?
‘ones’ and ‘twos’ are initialized as 0. For every new element in the array, find out the common set bits in the new element and the previous value of ‘ones’. These common set bits are actually the bits that should be added to ‘twos’. So do bitwise XOR of the common set bits with ‘twos’. ‘twos’ also gets some extra bits that appear the third time. These extra bits are removed later.
Update ‘ones’ by doing XOR of new element with the previous value of ‘ones’. There may be some bits that appear 3rd time. These extra bits are also removed later.
Both ‘ones’ and ‘twos’ contain those extra bits which appear 3rd time. Remove these extra bits by finding out common set bits in ‘ones’ and ‘twos’.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getSingle( int arr[], int n)
{
int ones = 0, twos = 0;
int common_bit_mask;
for ( int i = 0; i < n; i++) {
twos = twos | (ones & arr[i]);
ones = ones ^ arr[i];
common_bit_mask = ~(ones & twos);
ones &= common_bit_mask;
twos &= common_bit_mask;
}
return ones;
}
int main()
{
int arr[] = { 3, 3, 2, 3 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << "The element with single occurrence is "
<< getSingle(arr, n);
return 0;
}
|
C
#include <stdio.h>
int getSingle( int arr[], int n)
{
int ones = 0, twos = 0;
int common_bit_mask;
for ( int i = 0; i < n; i++) {
twos = twos | (ones & arr[i]);
ones = ones ^ arr[i];
common_bit_mask = ~(ones & twos);
ones &= common_bit_mask;
twos &= common_bit_mask;
}
return ones;
}
int main()
{
int arr[] = { 3, 3, 2, 3 };
int n = sizeof (arr) / sizeof (arr[0]);
printf ( "The element with single occurrence is %d " ,
getSingle(arr, n));
return 0;
}
|
Java
class GFG {
static int getSingle( int arr[], int n)
{
int ones = 0 , twos = 0 ;
int common_bit_mask;
for ( int i = 0 ; i < n; i++) {
twos = twos | (ones & arr[i]);
ones = ones ^ arr[i];
common_bit_mask = ~(ones & twos);
ones &= common_bit_mask;
twos &= common_bit_mask;
}
return ones;
}
public static void main(String args[])
{
int arr[] = { 3 , 3 , 2 , 3 };
int n = arr.length;
System.out.println( "The element with single occurrence is " + getSingle(arr, n));
}
}
|
Python3
def getSingle(arr, n):
ones = 0
twos = 0
for i in range (n):
twos = twos ^ (ones & arr[i])
ones = ones ^ arr[i]
common_bit_mask = ~(ones & twos)
ones & = common_bit_mask
twos & = common_bit_mask
return ones
arr = [ 3 , 3 , 2 , 3 ]
n = len (arr)
print ( "The element with single occurrence is " ,
getSingle(arr, n))
|
C#
using System;
class GFG {
static int getSingle( int [] arr, int n)
{
int ones = 0, twos = 0;
int common_bit_mask;
for ( int i = 0; i < n; i++) {
twos = twos | (ones & arr[i]);
ones = ones ^ arr[i];
common_bit_mask = ~(ones & twos);
ones &= common_bit_mask;
twos &= common_bit_mask;
}
return ones;
}
public static void Main()
{
int [] arr = { 3, 3, 2, 3 };
int n = arr.Length;
Console.WriteLine( "The element with single"
+ "occurrence is " + getSingle(arr, n));
}
}
|
PHP
<?php
function getSingle( $arr , $n )
{
$ones = 0; $twos = 0 ;
$common_bit_mask ;
for ( $i = 0; $i < $n ; $i ++ )
{
$twos = $twos | ( $ones & $arr [ $i ]);
$ones = $ones ^ $arr [ $i ];
$common_bit_mask = ~( $ones & $twos );
$ones &= $common_bit_mask ;
$twos &= $common_bit_mask ;
}
return $ones ;
}
$arr = array (3, 3, 2, 3);
$n = sizeof( $arr );
echo "The element with single " .
"occurrence is " ,
getSingle( $arr , $n );
?>
|
Javascript
<script>
function getSingle(arr, n)
{
let ones = 0, twos = 0;
let common_bit_mask;
for (let i = 0; i < n; i++) {
twos = twos | (ones & arr[i]);
ones = ones ^ arr[i];
common_bit_mask = ~(ones & twos);
ones &= common_bit_mask;
twos &= common_bit_mask;
}
return ones;
}
let arr = [ 3, 3, 2, 3 ];
let n = arr.length;
document.write( "The element with single occurrence is " + getSingle(arr, n));
</script>
|
Output
The element with single occurrence is 2
Time Complexity: O(n)
Auxiliary Space: O(1)
Following is another O(n) time complexity and O(1) extra space method suggested by aj. We can sum the bits in the same positions for all the numbers and take modulo with 3. The bits for which sum is not multiple of 3, are the bits of number with single occurrence.
Let us consider the example array {5, 5, 5, 8}. The 101, 101, 101, 1000
Sum of first bits%3 = (1 + 1 + 1 + 0)%3 = 0;
Sum of second bits%3 = (0 + 0 + 0 + 0)%3 = 0;
Sum of third bits%3 = (1 + 1 + 1 + 0)%3 = 0;
Sum of fourth bits%3 = (1)%3 = 1;
Hence number which appears once is 1000
Note: this approach won’t work for negative numbers
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define INT_SIZE 32
int getSingle( int arr[], int n)
{
int result = 0;
int x, sum;
for ( int i = 0; i < INT_SIZE; i++) {
sum = 0;
x = (1 << i);
for ( int j = 0; j < n; j++) {
if (arr[j] & x)
sum++;
}
if ((sum % 3) != 0)
result |= x;
}
return result;
}
int main()
{
int arr[] = { 12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << "The element with single occurrence is " << getSingle(arr, n);
return 0;
}
|
C
#include <stdio.h>
#define INT_SIZE 32
int getSingle( int arr[], int n)
{
int result = 0;
int x, sum;
for ( int i = 0; i < INT_SIZE; i++) {
sum = 0;
x = (1 << i);
for ( int j = 0; j < n; j++) {
if (arr[j] & x)
sum++;
}
if ((sum % 3) != 0)
result |= x;
}
return result;
}
int main()
{
int arr[] = { 12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7 };
int n = sizeof (arr) / sizeof (arr[0]);
printf ( "The element with single occurrence is %d " ,
getSingle(arr, n));
return 0;
}
|
Java
class GFG {
static final int INT_SIZE = 32 ;
static int getSingle( int arr[], int n)
{
int result = 0 ;
int x, sum;
for ( int i = 0 ; i < INT_SIZE; i++) {
sum = 0 ;
x = ( 1 << i);
for ( int j = 0 ; j < n; j++) {
if ((arr[j] & x) != 0 )
sum++;
}
if ((sum % 3 ) != 0 )
result |= x;
}
return result;
}
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;
System.out.println( "The element with single occurrence is " + getSingle(arr, n));
}
}
|
Python3
INT_SIZE = 32
def getSingle(arr, n) :
result = 0
for i in range ( 0 , INT_SIZE) :
sm = 0
x = ( 1 << i)
for j in range ( 0 , n) :
if (arr[j] & x) :
sm = sm + 1
if ((sm % 3 )! = 0 ) :
result = result | x
return result
arr = [ 12 , 1 , 12 , 3 , 12 , 1 , 1 , 2 , 3 , 2 , 2 , 3 , 7 ]
n = len (arr)
print ( "The element with single occurrence is " , getSingle(arr, n))
|
C#
using System;
class GFG {
static int INT_SIZE = 32;
static int getSingle( int [] arr, int n)
{
int result = 0;
int x, sum;
for ( int i = 0; i < INT_SIZE; i++) {
sum = 0;
x = (1 << i);
for ( int j = 0; j < n; j++) {
if ((arr[j] & x) != 0)
sum++;
}
if ((sum % 3) != 0)
result |= x;
}
return result;
}
public static void Main()
{
int [] arr = { 12, 1, 12, 3, 12, 1,
1, 2, 3, 2, 2, 3, 7 };
int n = arr.Length;
Console.WriteLine( "The element with single "
+ "occurrence is " + getSingle(arr, n));
}
}
|
PHP
<?php
$INT_SIZE = 32;
function getSingle( $arr , $n )
{
global $INT_SIZE ;
$result = 0;
$x ; $sum ;
for ( $i = 0; $i < $INT_SIZE ; $i ++)
{
$sum = 0;
$x = (1 << $i );
for ( $j = 0; $j < $n ; $j ++ )
{
if ( $arr [ $j ] & $x )
$sum ++;
}
if (( $sum % 3) !=0 )
$result |= $x ;
}
return $result ;
}
$arr = array (12, 1, 12, 3, 12, 1,
1, 2, 3, 2, 2, 3, 7);
$n = sizeof( $arr );
echo "The element with single occurrence is " ,
getSingle( $arr , $n );
?>
|
Javascript
<script>
let INT_SIZE = 32;
function getSingle(arr, n)
{
let result = 0;
let x, sum;
for (let i = 0; i < INT_SIZE; i++)
{
sum = 0;
x = (1 << i);
for (let j = 0; j < n; j++)
{
if (arr[j] & x)
sum++;
}
if ((sum % 3) != 0)
result |= x;
}
return result;
}
let arr = [ 12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7 ];
let n = arr.length;
document.write( "The element with single occurrence is " + getSingle(arr, n));
</script>
|
Output
The element with single occurrence is 7
Time Complexity: O(n)
Auxiliary Space: O(1)
Another approach suggested by Abhishek Sharma 44. Add each number once and multiply the sum by 3, we will get thrice the sum of each element of the array. Store it as thrice_sum. Subtract the sum of the whole array from the thrice_sum and divide the result by 2. The number we get is the required number (which appears once in the array).
Array [] : [a, a, a, b, b, b, c, c, c, d]
Mathematical Equation = ( 3*(a+b+c+d) – (a + a + a + b + b + b + c + c + c + d) ) / 2
In more simple words: ( 3*(sum_of_array_without_duplicates) – (sum_of_array) ) / 2
let arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 3}
Required no = ( 3*(sum_of_array_without_duplicates) - (sum_of_array) ) / 2
= ( 3*(12 + 1 + 3 + 2) - (12 + 1 + 12 + 3 + 12 + 1 + 1 + 2 + 3 + 3))/2
= ( 3* 18 - 50) / 2
= (54 - 50) / 2
= 2 (required answer)
As we know that set does not contain any duplicate elements,
But, std::set is commonly implemented as a red-black binary search tree. Insertion on this data structure has a worst-case of O(log(n)) complexity, as the tree is kept balanced. we will be using set here.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int singleNumber( int a[], int n)
{
unordered_set< int > s(a, a + n);
int arr_sum = accumulate(a, a + n, 0);
int set_sum = accumulate(s.begin(), s.end(), 0);
return (3 * set_sum - arr_sum) / 2;
}
int main()
{
int a[] = { 12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7 };
int n = sizeof (a) / sizeof (a[0]);
cout << "The element with single occurrence is " << singleNumber(a, n);
}
|
Java
import java.util.*;
class GFG {
static int singleNumber( int a[], int n)
{
HashSet<Integer> s = new HashSet<Integer>();
for ( int i : a) {
s.add(i);
}
int arr_sum = 0 ;
for ( int i : a) {
arr_sum += i;
}
int set_sum = 0 ;
for ( int i : s) {
set_sum += i;
}
return ( 3 * set_sum - arr_sum) / 2 ;
}
public static void main(String[] args)
{
int a[] = { 12 , 1 , 12 , 3 , 12 , 1 , 1 , 2 , 3 , 2 , 2 , 3 , 7 };
int n = a.length;
System.out.println( "The element with single "
+ "occurrence is " + singleNumber(a, n));
}
}
|
Python3
def singleNumber(nums):
return ( 3 * sum ( set (nums)) - sum (nums)) / 2
a = [ 12 , 1 , 12 , 3 , 12 , 1 , 1 , 2 , 3 , 2 , 2 , 3 , 7 ]
print ( "The element with single occurrence is " ,
int (singleNumber(a)))
|
C#
using System;
using System.Collections.Generic;
class GFG {
static int singleNumber( int [] a, int n)
{
HashSet< int > s = new HashSet< int >();
foreach ( int i in a)
{
s.Add(i);
}
int arr_sum = 0;
foreach ( int i in a)
{
arr_sum += i;
}
int set_sum = 0;
foreach ( int i in s)
{
set_sum += i;
}
return (3 * set_sum - arr_sum) / 2;
}
public static void Main(String[] args)
{
int [] a = { 12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7 };
int n = a.Length;
Console.WriteLine( "The element with single "
+ "occurrence is " + singleNumber(a, n));
}
}
|
PHP
<?php
function singleNumber( $a , $n )
{
$s = array ();
for ( $i = 0; $i < count ( $a ); $i ++)
array_push ( $s , $a [ $i ]);
$s = array_values ( array_unique ( $s ));
$arr_sum = 0;
for ( $i = 0; $i < count ( $a ); $i ++)
{
$arr_sum += $a [ $i ];
}
$set_sum = 0;
for ( $i = 0; $i < count ( $s ); $i ++)
{
$set_sum += $s [ $i ];
}
return (int)(((3 * $set_sum ) -
$arr_sum ) / 2);
}
$a = array (12, 1, 12, 3, 12, 1,
1, 2, 3, 2, 2, 3, 7);
$n = count ( $a );
print ( "The element with single occurrence is " .
singleNumber( $a , $n ));
?>
|
Javascript
<script>
function singleNumber(a,n)
{
let s = new Set(a);
let arr_sum = 0;
for (let i=0;i<a.length;i++)
{
arr_sum += a[i];
}
let set_sum = 0;
for (let i of s)
{
set_sum +=i;
}
return Math.floor((3 * set_sum - arr_sum) / 2);
}
let arr=[12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7 ];
let n = arr.length;
document.write( "The element with single "
+ "occurrence is " + singleNumber(arr, n));
</script>
|
Output
The element with single occurrence is 7
Time Complexity: O(N log(N))
Auxiliary Space: O(N)
Method #4:Using Counter() function
- Calculate the frequency of array using Counter function
- Traverse in this Counter dictionary and check if any key has value 1
- If the value of any key is 1 return the key
Below is the implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int singlenumber( int a[], int N)
{
unordered_map< int , int >fmap;
for ( int i = 0; i < N;i++)
{
fmap[a[i]]++;
}
for ( auto it:fmap)
{
if (it.second == 1)
{
return it.first;
}
}
}
int main()
{
int a[]={12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7};
int N= sizeof (a)/ sizeof (a[0]);
cout << singlenumber(a,N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static int singlenumber( int a[], int N)
{
Map<Integer, Integer> fmap
= new HashMap<Integer, Integer>();
for ( int i = 0 ; i < N;i++)
{
if (!fmap.containsKey(a[i]))
fmap.put(a[i], 0 );
fmap.put(a[i],fmap.get(a[i])+ 1 );
}
for (Map.Entry<Integer, Integer> me : fmap.entrySet())
{
if (me.getValue()== 1 )
{
return me.getKey();
}
}
return - 1 ;
}
public static void main (String[] args) {
int a[]={ 12 , 1 , 12 , 3 , 12 , 1 , 1 , 2 , 3 , 2 , 2 , 3 , 7 };
int N= a.length;
System.out.println( "The element with single occurrence is " +singlenumber(a,N));
}
}
|
Python3
from collections import Counter
def singleNumber(nums):
freq = Counter(nums)
for i in freq:
if (freq[i] = = 1 ):
return i
a = [ 12 , 1 , 12 , 3 , 12 , 1 , 1 , 2 , 3 , 2 , 2 , 3 , 7 ]
print ( "The element with single occurrence is " ,
int (singleNumber(a)))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG {
static void singlenumber( int [] a, int N)
{
Dictionary< int , int > fmap = new Dictionary< int , int >();
for ( int i = 0; i < N; i++)
{
if (fmap.ContainsKey(a[i]))
fmap[a[i]]++;
else
fmap.Add(a[i], 1);
}
foreach ( int it in fmap.Keys.ToList())
{
if (fmap[it] == 1)
{
Console.Write( "The element with single occurrence is " + it);
}
}
}
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;
singlenumber(arr, n);
}
}
|
Javascript
<script>
function singlenumber(a,N)
{
let fmap= new Map();
for (let i = 0; i < N;i++)
{
if (!fmap.has(a[i]))
fmap.set(a[i],0);
fmap.set(a[i],fmap.get(a[i])+1);
}
for (let [key, value] of fmap.entries())
{
if (value==1)
{
return key;
}
}
}
let a = [12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7];
let N = a.length;
document.write( "The element with single occurrence is " +singlenumber(a,N));
</script>
|
Output
The element with single occurrence is 7
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #5 : Using count() method.
We can find the occurrence of elements using count() method. If count() method returns 1 then the element has a single occurrence.
C++
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector< int > arr{3, 3, 2, 3};
int x;
for ( int i : arr)
{
if (count(arr.begin(), arr.end(), i) == 1)
{
x = i;
break ;
}
}
cout << "The element with single occurrence is " << x << endl;
return 0;
}
|
Java
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>(Arrays.asList( 3 , 3 , 2 , 3 ));
int x = 0 ;
for ( int i : arr) {
if (Collections.frequency(arr, i) == 1 ) {
x = i;
break ;
}
}
System.out.println( "The element with single occurrence is " + x);
}
}
|
Python3
arr = [ 3 , 3 , 2 , 3 ]
for i in arr:
if (arr.count(i) = = 1 ):
x = i
break
print ( "The element with single occurrence is " ,x)
|
C#
using System;
using System.Linq;
public class GFG
{
public static void Main( string [] args)
{
int [] nums = { 3, 3, 2, 3};
foreach ( int i in nums)
{
if (nums.Count(n => n==i)==1)
Console.WriteLine( "The element with single occurrence is " +i);
}
}
}
|
Javascript
const arr = [3, 3, 2, 3];
let x;
for (let i of arr) {
if (arr.filter(num => num === i).length === 1) {
x = i;
break ;
}
}
console.log(`The element with single occurrence is ${x}`);
|
Output
The element with single occurrence is 2
Time Complexity: O(n^2)
Auxiliary Space: O(1)
This article is compiled by Sumit Jain and reviewed by the GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
16 Feb, 2023
Like Article
Save Article