Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the element that appears once

Tags:

algorithm

Find the element that appears once

Given an array where every element occurs three times, except one element which occurs only once. Find the element that occurs once.

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

like image 580
kamal Avatar asked Dec 31 '12 10:12

kamal


People also ask

How do you find unique elements using XOR?

The way to find the unique element is by using the XOR bitwise operator which returns 1 only if one of the element is 1 and false otherwise. In the loop, each of the integers in the array are XORed with uniqueId starting at 0. Then, 0 is XOR'ed with 34.

How do you find unpaired elements in an array?

Naive Approach In the naive approach, we try to search the array linearly for the pair of each element. Once we find an element that doesn't have a pair, we declare it as the answer to the problem. loop. , then the current element was unpaired.


1 Answers

If O(1) space constraint was not there, you could've gone for a hashmap with values being the count of occurrences.

int getUniqueElement(int[] arr)
{
    int ones = 0 ; //At any point of time, this variable holds XOR of all the elements which have appeared "only" once.
    int twos = 0 ; //At any point of time, this variable holds XOR of all the elements which have appeared "only" twice.
    int not_threes ;

    for( int x : arr )
    {
        twos |= ones & x ; //add it to twos if it exists in ones
        ones ^= x ; //if it exists in ones, remove it, otherwise, add it

        // Next 3 lines of code just converts the common 1's between "ones" and "twos" to zero.

        not_threes = ~(ones & twos) ;//if x is in ones and twos, dont add it to Threes.
        ones &= not_threes ;//remove x from ones
        twos &= not_threes ;//remove x from twos
    } 
    return ones;
}

Basically, it makes use of the fact that x^x = 0 and 0^x=x. So all paired elements get XOR'd and vanish leaving the lonely element.

In short :

If a bit is already in ones, add it to twos.

XOR will add this bit to ones if it's not there or remove this bit from ones if it's already there.

If a bit is in both ones and twos, remove it from ones and twos.

When finished, ones contains the bits that only appeared 3*n+1 times, which are the bits for the element that only appeared once.

like image 127
Rahul Avatar answered Oct 13 '22 00:10

Rahul