DEV Community

Cover image for Non-Repeating Number except two
Tisha Agarwal
Tisha Agarwal

Posted on

Non-Repeating Number except two

Given an array A containing 2*N+2 positive numbers, out of which 2*N numbers exist in pairs
whereas the other two number occur exactly once and are distinct. Find the other two numbers.

Example 1:
Input:
N = 2
arr[] = {1, 2, 3, 2, 1, 4}
Output:
3 4
Explanation:
3 and 4 occur exactly once.

So this is a MEDIUM LEVEL question on bit manipulation, asked in many companies like Amazon, Accolite, Google, MakeMyTrip.

To solve this question click here:(https://practice.geeksforgeeks.org/problems/finding-the-numbers0215/1)

Before starting you should know one basic properties of XOR:
(i) n ^ n=0 (XOR of two same elements is always 0)

1=0001
2=0010
3=0011
2=0010
1=0001
4=0100

1.First step is to find the XOR of all the elements.
(Since all the elements occur twice except two elements so all the elements will cancel each other out and the two unique elements will be left.eg: 1^2^3^2^1^4=3^4=0111 as 1^1=0 , 2^2=0 )

2.Suppose the XOR of all the elements is stored in variable 'res' , res=0111(3^4) then the next step is to find the right most set bit mask(rsbm) of res.(which is rsbm=0001)

3.Here the basic idea is to separate those elements with right most set bit 1 (rsbm=1) from the elements with rsbm=0 and then find the XOR of these elements separately, (for eg. find the XOR of 1,3,1 separately and 2,4,2 separately....1^3^1=3 and 2^4^2=4)

4.So after finding the XOR separately, we got the two unique elements present in the array.

JAVA CODE:

import java.util.*;
class Twonon_repeating_no {
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter a number:");
        int n=sc.nextInt();
        int[] arr=new int[n];
        System.out.println("Enter the elements of the array:");
        for(int i=0;i<n;i++){
            arr[i]=sc.nextInt();
        }

        int res=0;

        for(int i=0;i<n;i++){
            res=res^arr[i]; //XOR of all the elements
        }
        int rsbm=res & -res; //right most set bit mask of the XOR of the two unique element present in the array

        int x=0;
        int y=0;

        for(int i=0;i<n;i++)
        {
            if((arr[i] & rsbm)==0){
                x=x^arr[i];
            }
            else{
                y=y^arr[i];
            }
        }
        if(x>y){
            System.out.println(y);
            System.out.println(x);
        }
        else{
            System.out.println(x);
            System.out.println(y);

        }

    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)