Sort Integers by The Number of 1 Bits Problem
Description
LeetCode Problem 1356.
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.
Example 1:
Input: arr = [0,1,2,3,4,5,6,7,8]
Output: [0,1,2,4,8,3,5,6,7]
Explantion: [0] is the only integer with 0 bits.
[1,2,4,8] all have 1 bit.
[3,5,6] have 2 bits.
[7] has 3 bits.
The sorted array by bits is [0,1,2,4,8,3,5,6,7]
Example 2:
Input: arr = [1024,512,256,128,64,32,16,8,4,2,1]
Output: [1,2,4,8,16,32,64,128,256,512,1024]
Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order.
Constraints:
1 <= arr.length <= 5000 <= arr[i] <= 10^4
Solution
Approach: Sort by a Two-Part Key
The order asked for is a sort on the pair (number of 1 bits, value): first by the bit count, and among numbers with the same count, by the number itself. Any sort with that key gives the answer.
How to get the bit count:
- Python:
bin(x).count("1")(int.bit_countneeds Python 3.10). - Java
Integer.bitCount, C++__builtin_popcount, Gobits.OnesCount. - JavaScript has no built-in, so count with
x &= x - 1, which clears the lowest 1 bit each time.
Java, C++ and Go avoid a custom comparator with a packing trick: since every value is at most 104, which is below 100000, the number ones * 100000 + x orders exactly like the pair (ones, x). Add ones * 100000 to each element, sort the plain integers, then take every element % 100000 to get the values back.
Duplicates need no special care: equal numbers have equal keys and simply end up next to each other.
Complexity: O(n log n) time for the sort (counting bits is O(1) per number for 14-bit values), and O(1) extra space besides the sort itself (Python's sorted builds a new list).
class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
# Sort by (number of 1 bits, value).
return sorted(arr, key=lambda x: (bin(x).count("1"), x))