LeetCode Entry

1356. Sort Integers by The Number of 1 Bits

30.10.2023 easy 2023 kotlin

Sort an array comparing by bit count and value

1356. Sort Integers by The Number of 1 Bits easy blog post substack image.png

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/386

Problem TLDR

Sort an array comparing by bit count and value

Intuition

Let’s use some Kotlin API

Approach

  • countOneBits
  • sortedWith
  • compareBy

Complexity

  • Time complexity: \(O(nlog(n))\)

  • Space complexity: \(O(n)\)

Code


    fun sortByBits(arr: IntArray): IntArray = arr
      .sortedWith(compareBy({ it.countOneBits() }, { it }))
      .toIntArray()