




Sponsored
Sponsored
The basic idea is to use a custom key that calculates two parameters for sorting: the number of 1 bits in the binary representation and the integer value itself. This dual-key approach allows us to first sort by the number of 1 bits and then by the integer values in ascending order by default.
Time Complexity: O(n log n) due to the sorting operation.
Space Complexity: O(n) for storing the sorted array.
1import java.util.Arrays;
2
3public static int[] sortByBits(int[] arr) {
4    return Arrays.stream(arr)
5                 .boxed()
6                 .sorted((a, b) -> Integer.bitCount(a) == Integer.bitCount(b) ? a - b : Integer.bitCount(a) - Integer.bitCount(b))
7                 .mapToInt(i -> i)
8                 .toArray();
9}In this Java solution, we convert the integer array to a stream of boxed Integers, sort them using a custom comparator based on the count of 1-bits in their binary representation and then convert the sorted stream back to an int array.
Another approach is to first count the number of 1 bits for each integer and create a pair of this count and the integer. Then, sort the array of these pairs according to the count and original value.
Time Complexity: O(n log n) for sorting.
Space Complexity: O(1), sorting is done in place.
1function sortByBits(arr) {
2This JavaScript solution uses the Array.sort method with a custom comparator. It calculates the count of 1's by converting the number to binary and counting the 1's using string manipulation.