Sort Integers by The Number of 1 Bits — LeetCode 1356 Python Solution

EasyBit ManipulationArrayCountingSorting
Problem
#1356
Reading time
2 min

The 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 and in case of two or more integers have the same number of 1's you have to sort them in ascending order.

Example

Input
arr = [0,1,2,3,4,5,6,7,8]
Output
[0,1,2,4,8,3,5,6,7]

Python solution

Python
class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        return sorted(arr, key=lambda x: (x.bit_count(), x))

Complexity

MeasureComplexity
TimeO(n \log n)
SpaceO(n) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1356. Sort Integers by The Number of 1 Bits is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1356. Sort Integers by The Number of 1 Bits?
LeetCode 1356. Sort Integers by The Number of 1 Bits is rated Easy on LeetCode.
What is the time complexity of LeetCode 1356. Sort Integers by The Number of 1 Bits?
The Python solution on this page runs in O(n \log n).
What is the space complexity of LeetCode 1356. Sort Integers by The Number of 1 Bits?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1356. Sort Integers by The Number of 1 Bits cover?
LeetCode 1356. Sort Integers by The Number of 1 Bits is tagged Bit Manipulation, Array, Counting and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview