• + 9 comments

    Java solution - passes 100% of test cases

    O(n) runtime. O(1) space. Uses XOR. Keep in mind:

    1. x ^ x = 0
    2. x ^ 0 = x
    3. XOR is commutative and associative
    public static int lonelyInteger(int [] array) {
        int val = 0;
        for (int num : array) {
            val = val ^ num; // ^ is XOR operator
        }
        return val;
    }
    

    From my HackerRank Java solutions.