Sort Integers by The Number of 1 Bits - Problem

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.

In case of two or more integers have the same number of 1's, you have to sort them in ascending order by their decimal values.

Return the array after sorting it.

Input & Output

Example 1 — Basic Case
$ Input: arr = [0,1,1,2]
Output: [0,1,1,2]
💡 Note: 0 has 0 bits, 1 has 1 bit each, 2 has 1 bit. Sorting by bit count: [0] (0 bits), then [1,1,2] (1 bit each, sorted by value)
Example 2 — Multiple Same Bit Counts
$ Input: arr = [1,5,3,7]
Output: [1,3,5,7]
💡 Note: All have same bit count (1=1 bit, 5=2 bits, 3=2 bits, 7=3 bits). First 1 (1 bit), then 3,5 (2 bits, sorted by value), then 7 (3 bits)
Example 3 — Edge Case with Zero
$ Input: arr = [0,8,4,2,1]
Output: [0,1,2,4,8]
💡 Note: 0 has 0 bits, 1,2,4,8 each have 1 bit. Result: 0 first, then 1,2,4,8 sorted by value

Constraints

  • 1 ≤ arr.length ≤ 500
  • 0 ≤ arr[i] ≤ 104

Visualization

Tap to expand
Sort Integers by Number of 1 BitsInput: [0, 1, 1, 2]011200000001000100100 bits1 bit1 bit1 bitSort by: 1) bit count, 2) value0112Output: [0, 1, 1, 2] - sorted by bit count, then value
Understanding the Visualization
1
Input Array
Original array: [0,1,1,2]
2
Count 1-bits
0→0 bits, 1→1 bit, 1→1 bit, 2→1 bit
3
Sorted Output
Sort by bit count, then by value: [0,1,1,2]
Key Takeaway
🎯 Key Insight: Use custom sorting with bit count as primary key and original value as secondary key
Asked in
Amazon 15 Microsoft 12 Apple 8
64.6K Views
Medium Frequency
~15 min Avg. Time
1.8K 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