Program to find the element which occur only once in an array

  • Post author:
  • Reading time:1 mins read

Given an array with every element repeated twice except one. Find that element

In the solution we perform the XOR operation on all the elements in the array and store the result in a variable.

The XOR of any number with itself gives 0 as output.

The XOR of any number with 0 gives the number itself as output.

 

Program:

public class FindSingleElement {

	public static void main(String[] args) {

		int arr[]= {1,1,2,2,3,3,4,5,5,6,6};
		int res=0;

		for(int i=0; i<arr.length; i++)
			res= (res | arr[i]) & (~res | ~arr[i]);

		System.out.println("Element occurring only once is: "+res);
	}
}

Output:

Element occurring only once is: 4

 

Leave a Reply