4.07.2023
137. Single Number II medium
blog post
Join me on Telegram
https://t.me/leetcode_daily_unstoppable/265
Problem TLDR
Single number in an array of triples
Intuition
One simple approach it to count bits at each position.
Result will have a 1
when count % 3 != 0
.
Approach
Let’s use fold.
Complexity
Time complexity:
O(n)Space complexity:
O(1)
Code
fun singleNumber(nums: IntArray): Int =
//110
//110
//110
//001
//001
//001
//010
//010
//010
//100
//463
(0..31).fold(0) { res, bit ->
res or ((nums.count { 0 != it and (1 shl bit) } % 3) shl bit)
}