HackerRank contest: Count of pairs whose bitwise AND is a power of 2

I was recently attending a coding contest from HackerRank. I wasn't able to produce an Optimal solution.

Question:
Calculate the number of unordered pairs in an array whose bitwise “AND” is a power of 2:

My brute force solution in Kotlin:

fun countPairs(arr: Array<Int>): Long {
    var ans = 0L
    for(i in arr.indices) {
        for (j in i+1 until arr.size) {
            val bitAnd = arr[i] and arr[j]
            if((bitAnd and (bitAnd -1)) == 0 && bitAnd != 0) {
                ans++
            }
        }
    }
    return ans
}

Please help me with the most efficient solution -possibly O(n) or O(n*log(n)).

Comments (4)