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
Sort Integers by Number of 1-BitsStep 1: Binary Representation7111โ‚‚3 ones11โ‚‚1 one311โ‚‚2 onesStep 2: Group by Bit Count1 bit group:12 bits group:33 bits group:7Final Result: [1, 3, 7]137
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!
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
98.4K Views
Medium Frequency
~12 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen