• + 0 comments

    Java:

    Using bitwise operator will be time complexity of O(n) without requiring addition memory space.

    when we use xor between same number,

    7^7 = (0111)^(0111) -> 0^0 = 0, 1^1 = 0

    therefore,

    7^7 = 0000 -> its decimal value becomes zero

    conclusion: xor with same number provide zero.

    when we use xor between any value and zero,

    7^0 = (0111)^(0000) -> 0^0 = 0, 1^0 = 1

    therefore,

    7^0 = 0111 -> its decimal value becomes 7 (same number)

    conclusion: xor with a number provide the same number. No effect when we xor a value with zero

    Also, 7^4^7 is same as 7^7^4

    7^7^4 -> (7^7)^4 -> 0^4 (xor between same value is zero)

    0^4 -> 4 (xor a value with zero provides the same value)

    Now with more values,

    7^4^5^7^5 -> (7^7)^(5^5)^4 ->0^0^4 -> 4

    Since hackerrank gurantees only one unique element always there, so we can just use xor across the list and return the final output.

        // Write your code here
            int value = a.get(0);
            for(int i=1; i<a.size(); i++){
                value ^= a.get(i); 
            }
             
            return value;
        }