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 The Number of 1 Bits INPUT arr = [0, 1, 1, 2] 0 1 1 2 Binary Representations: 0000 0001 0001 0010 Count of 1-bits: 0 1 1 1 Sort by bit count, then value ALGORITHM STEPS 1 Count 1-bits Use popcount/bitcount 2 Custom Comparator Compare by bit count first 3 Tie-breaker If equal bits, sort by value 4 Built-in Sort Apply stable sort Comparator Logic: if bits(a) != bits(b): return bits(a) < bits(b) else: return a < b FINAL RESULT Output: [0, 1, 1, 2] 0 1 1 2 0 bits 1 bit 1 bit 1 bit Sorting Order: 0 has 0 ones --> first 1 has 1 one --> second 1 has 1 one --> third (tie) 2 has 1 one --> fourth (2>1) OK - Sorted! Key Insight: Use a custom comparator that first compares the popcount (number of 1-bits) of two numbers. When bit counts are equal, fall back to comparing the actual decimal values. Time: O(n log n). TutorialsPoint - Sort Integers by The Number of 1 Bits | Built-in Sort with Custom Comparator
Asked in
Amazon 15 Microsoft 12 Apple 8
64.7K 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