Sort Integers by The Number of 1 Bits
Given an integer array arr, sort the array in ascending order by the number of 1 bits in the binary representation of each integer. If two integers have the same number of 1 bits, sort them by ascending value.
Count the number of 1 bits (popcount) for each integer. The popcount can be computed using built-in functions like Integer.bitCount in Java or bit_count in Python, or via a manual loop. Then sort with a custom comparator: compare popcount first, then value for ties.
Time is O(n log n) for sorting plus O(n) for counting bits. Space is O(1).
Edge cases include an empty array, single element, all zero values (bit count 0), and large numbers with many bits.
The popcount operation counts 1 bits in binary representation. Combined with custom sorting, this reveals patterns about how numbers relate to powers of two and demonstrates secondary sorting when primary keys are equal. The bit count sorting problem demonstrates how binary representation properties can be used as sort keys. The custom comparator first compares bit counts, with value comparison as a secondary tiebreaker to ensure a deterministic ordering. The popcount comparison uses the built-in bit counting function available in most modern programming languages, often mapping to a single CPU instruction for efficiency.Example Input & Output
8(1bit),3(2),5(2),7(3). Tie: 3<5.
All have 1 bit, sort by value.
Empty.
Bit count order: 0(0),1(1),2(1),4(1),8(1),3(2),5(2),6(2),7(3).
1(1bit), 2(1bit), 3(2bits). Tie: 1<2.
Algorithm Flow

Solution Approach
For each element, compute its bit count. Sort by bit count ascending, then by value ascending for ties.
Time O(n log n), Space O(1).
Best Answers
import java.util.*;
class Solution {
public int[] solution(int[] arr) {
Integer[] boxed=Arrays.stream(arr).boxed().toArray(Integer[]::new);
Arrays.sort(boxed,(a,b)->{
int ca=Integer.bitCount(a),cb=Integer.bitCount(b);
if(ca!=cb)return ca-cb;
return a-b;
});
return Arrays.stream(boxed).mapToInt(i->i).toArray();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
