Problem statement

https://binarysearch.com/problems/Sort-List-by-Hamming-Weight/

Solution

Equal to Leetcode 1356. Sort Integers by The Number of 1 Bits.

Complexity

It is O(n log n + n log M) for time and O(n) for space.

Code

class Solution:
    def solve(self, A):
        return sorted(A, key = lambda x: (bin(x).count("1"), x))