Skip to content

HackerRank Solutions – Bit Manipulation – Lonely Integer – Java Solution

All credits to Rodney Shaghoulian for this simple solution for the HackerRank challenge – Bit Manipulation – Lonely Integer. This solution is written in Java.

// Author: Rodney Shaghoulian
// Github: github.com/RodneyShag

// 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

int findLonely(List<Integer> array) {
    int val = 0;
    for (int num : array) {
        val = val ^ num; // ^ is XOR operator
    }
    return val;
}
    
See also  Java List - Hackerrank Challenge - Java Solution

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.