#1356
Easy Algorithms Sort integers by the number of 1 bits
Array Bit Manipulation Sorting Counting
82.3% acceptance
Feb 25, 2026
2853
136
You are given an integer array arr. Sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.
Return the array after sorting it.
Solution
Rust
Time O(1)
Space O(1)
impl Solution {
pub fn sort_by_bits(mut arr: Vec<i32>) -> Vec<i32> {
arr.sort_unstable_by_key(|&x| (x.count_ones(), x));
arr
}
}