LeetCode Entry

137. Single Number II

4.07.2023 medium 2023 kotlin

Let's use fold.

137. Single Number II medium blog post substack image.png

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/265

Proble TLDR

Single number in an array of tripples

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)
}