How to find the number occurring an odd number of times in a list with Kotlin

1 Answer

0 votes
fun oddOccurrence(nums: List<Int>): Int {
    // XOR all elements
    val xorValue = nums.fold(0) { acc, n -> acc xor n }

    // Verify that this value actually appears
    return nums.find { it == xorValue } ?: -1
}

fun main() {
    val lst = listOf(2, 3, 7, 2, 8, 8, 8, 8, 3, 0, 0, 7, 7)
    
    println(oddOccurrence(lst))
}



/*
run:

7

*/

 



answered Jan 30 by avibootz

Related questions

...