Find the unique number in an array

Find the unique number in an array

Find the unique number in an array where all the elements are repeated twice. All the numbers are positive.

Answer : Let array be Arr = [1,2,3,4,2,1,3];

Here the number 4 is unique and all other numbers are being repeaated twice.

So, we will traverse through the array using two loops comparing each element with the other array element and if any of them matches we will assign them value -1.

And then we will traverse the array and the number greater than 0 will be the unique number.

The code will be as follows :

public class uniNum {
    public static void main(String[] args) {
        int [] arr = {1,3,2,4,3,2,1};
        for(int i=0; i<arr.length; i++){
            for(int j=i+1;j<arr.length;j++){
                if(arr[i] == arr[j]){
                    arr[i] = arr[j] = -1;
                }
            }
        }

        for(int i=0; i<arr.length; i++){
            if(arr[i] > 0){
                System.out.println("The number is : "+arr[i]);
            }
        }
    }
}