LeetCode Entry

1356. Sort Integers by The Number of 1 Bits

25.02.2026 easy 2026 kotlin rust

Sort

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

9a58f8d1-aaaa-4b92-a674-3a6792b31633 (1).webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1280

Problem TLDR

Sort #easy

Intuition

Sort.

Approach

  • you can use 15 buckets (32 bits, and even less for 10^4 max test case)
  • still have to sort

Complexity

  • Time complexity: \(O(nlogn)\)

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

Code

// 18ms
    fun sortByBits(a: IntArray) =
    a.sortedBy{it.countOneBits()*1e5+it}
// 0ms
    pub fn sort_by_bits(mut a: Vec<i32>) -> Vec<i32> {
        a.sort_by_key(|&x|(x.count_ones(),x)); a
    }