Sort Integers by The Number of 1 Bits - Problem
Imagine you have an array of integers, and you need to sort them in a unique way! Instead of sorting by their actual values, you need to sort them by how many 1's appear in their binary representation.
Here's the twist: when two numbers have the same number of 1-bits, you should sort them in ascending numerical order as a tiebreaker.
For example, the number 7 in binary is 111 (three 1's), while 4 in binary is 100 (one 1). So 4 should come before 7 in our special sorting.
Goal: Return the array sorted by the count of 1-bits in each number's binary representation, with numerical order as the tiebreaker.
Input & Output
example_1.py โ Basic sorting
$
Input:
[0,1,2,3,4,5,6,7,8]
โบ
Output:
[0,1,2,4,8,3,5,6,7]
๐ก Note:
0(0 bits), 1(1 bit), 2(1 bit), 4(1 bit), 8(1 bit) come first. Then 3(2 bits), 5(2 bits), 6(2 bits), and finally 7(3 bits). Within each group, numbers are sorted in ascending order.
example_2.py โ Mixed values
$
Input:
[1024,512,256,128,64,32,16,8,4,2,1]
โบ
Output:
[1,2,4,8,16,32,64,128,256,512,1024]
๐ก Note:
All powers of 2 have exactly 1 bit set in their binary representation, so they are sorted by their actual values in ascending order.
example_3.py โ Same bit counts
$
Input:
[10,100,1000,10000]
โบ
Output:
[10,100,1000,10000]
๐ก Note:
10(2 bits: 1010), 100(3 bits: 1100100), 1000(4 bits: 1111101000), 10000(5 bits: 10011100010000). Each has different bit counts, so original order is maintained within each group.
Constraints
- 1 โค arr.length โค 500
- 0 โค arr[i] โค 104
- Follow up: Can you solve this in O(n log n) time complexity?
Visualization
Tap to expand
Understanding the Visualization
1
Convert to Binary
Each number shows its binary representation and bit count
2
Group by Bit Count
Numbers are grouped by their 1-bit count
3
Sort Within Groups
Within each group, sort by numerical value
4
Final Arrangement
Combine groups in ascending order of bit counts
Key Takeaway
๐ฏ Key Insight: Use a tuple `(bit_count, value)` as the sorting key to handle primary sorting by bit count and automatic tie-breaking by value!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code