Sort Integers by The Number of 1 Bits (LeetCode 1356): Solution and Explanation

Easy
Array
Bit Manipulation
Sorting
Counting

Order the array by how many 1 bits each value has, breaking ties by the value itself.

Intuition

The order has two keys: the count of 1 bits first, and the value second. Any approach just has to respect both.

The bit count is small. A value up to 10^4 fits in 14 bits, so it has at most 13 ones. That makes a bucket per count cheap: 15 buckets cover every case.

Ties are settled for free if the values go into the buckets in ascending order. So sort by value once, drop each value into the bucket for its bit count, and every bucket comes out sorted. Reading the buckets from 0 ones upward is the answer.

Approach: Sort by value, then bucket by bit count

  1. Copy arr and sort it by value.
  2. Create 15 empty buckets, one per possible count of 1 bits.
  3. For each value in sorted order, count its 1 bits and append it to that bucket.
  4. Concatenate the buckets from bucket 0 to bucket 14 and return the result.

Step-by-step example

arr = [0,1,2,3,4,5,6,7,8]
  1. Sorted by value it is already [0,1,2,3,4,5,6,7,8].
  2. 0 has no ones: bucket 0 = [0].
  3. 1, 2, 4 and 8 have one 1 bit: bucket 1 = [1,2,4,8].
  4. 3 (11), 5 (101) and 6 (110) have two: bucket 2 = [3,5,6].
  5. 7 (111) has three: bucket 3 = [7].
  6. Read the buckets in order: [0,1,2,4,8,3,5,6,7].

Code: Python, Java, C++

1class Solution:
2    def sortByBits(self, arr: List[int]) -> List[int]:
3        nums = sorted(arr)
4        buckets = [[] for _ in range(15)]
5        for x in nums:
6            buckets[bin(x).count('1')].append(x)
7        result = []
8        for bucket in buckets:
9            result.extend(bucket)
10        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log n)

The value sort costs O(n log n). Counting bits is O(14) per value and pouring the buckets is O(n).

Space

O(n)

The sorted copy, the buckets and the result each hold n values.

Other approaches

Sort with a two-part key (time O(n log n), space O(n))

Sort with the key (bit count, value), for example sorted(arr, key=lambda x: (bin(x).count('1'), x)) in Python or a comparator in Java. Shortest to write.

Encode both keys in one integer (time O(n log n), space O(n))

Since values are at most 10^4, sort the numbers bitCount(x) * 100000 + x as plain integers, then take each one modulo 100000. Avoids a custom comparator in languages where that is awkward.

Common mistakes

  • Forgetting the tie-break. Sorting by bit count alone with an unstable sort can put 5 before 3.
  • Bucketing the unsorted array. The buckets then keep input order, so 6 can end up ahead of 3 inside bucket 2.
  • Sizing the buckets too small. 8191 has 13 ones, so you need at least 14 buckets.

Frequently asked questions

Why does sorting by value first make each bucket sorted?

Values are appended to a bucket in the order they are visited. If they are visited in ascending order, each bucket only ever receives larger or equal values, so it stays sorted.

How do I count 1 bits without a library call?

Repeat x = x & (x - 1) until x is 0 and count the steps. Each step clears the lowest 1 bit, so the number of steps is the number of ones.

Can this be done in linear time?

Yes, by replacing the value sort with a counting sort, since values are at most 10^4. For arrays of at most 500 values the comparison sort is simpler and just as fast in practice.