Sort array according to count of set bits
Pattern: Counting bits
Put each value in a bucket numbered by its set-bit count, keeping input order within a bucket. Read the buckets from 32 down to 0. That is a stable sort by set bits, most first, in O(n).
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Given an array of non-negative whole numbers, sort it in decreasing order of the number of set bits. Values with the same
count keep their original order. For example, [5, 2, 3, 9, 4, 6, 7, 15, 32] gives [15, 7, 5, 3, 9, 6, 2, 4, 32].
This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name
sortBySetBitCount is this guide's own.
Think first
- What key decides the order?
- How many different keys can there be?
- How do you keep equal keys in their input order?
Hints
Brute force, and why it fails
A stable comparison sort by -popcount: O(n log n). Buckets: O(n).
The key insight
When the sort key has only a few possible values, counting into buckets is faster than comparing, and it is naturally stable.
Dry run
arr = [5, 2, 3, 9, 4, 6, 7, 15, 32]. Their set-bit counts are 2, 1, 2, 2, 1, 2, 3, 4, 1.
The plan
buckets = 33 empty lists
for v in arr: append v to buckets[popcount(v)]
return the buckets from 32 down to 0, concatenated
Complexity
- Time
O(n)- Space
O(n)
Each value is counted once (at most 32 steps) and placed once.
Edge cases
- All the same count: unchanged.
- Zeros: they go last.
- One value: itself.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int[] sortBySetBitCount(int[] arr) {
List<List<Integer>> buckets = new ArrayList<>(); // buckets.get(c): values with c set bits, in input order
for (int c = 0; c <= 32; c++) buckets.add(new ArrayList<>());
for (int v : arr) buckets.get(Integer.bitCount(v)).add(v);
int[] out = new int[arr.length];
int k = 0;
for (int c = 32; c >= 0; c--) for (int v : buckets.get(c)) out[k++] = v; // most set bits first
return out;
}
}C++
class Solution {
public:
vector<int> sortBySetBitCount(vector<int>& arr) {
vector<vector<int>> buckets(33); // buckets[c]: values with c set bits, in input order
for (int v : arr) {
int c = 0;
for (unsigned int x = static_cast<unsigned int>(v); x; x &= x - 1) c++;
buckets[c].push_back(v);
}
vector<int> out;
for (int c = 32; c >= 0; c--) for (int v : buckets[c]) out.push_back(v); // most set bits first
return out;
}
};Python
class Solution:
def sortBySetBitCount(self, arr: list[int]) -> list[int]:
buckets = [[] for _ in range(33)] # buckets[c]: values with c set bits, in input order
for v in arr:
buckets[bin(v).count("1")].append(v)
return [v for c in range(32, -1, -1) for v in buckets[c]] # most set bits firstCommon mistakes
- Using an unstable sort, which can reorder equal counts.
- Sorting in increasing order of set bits.
- Recomputing popcounts inside a comparator, which is slower.