Array Bit Manipulation Counting Sorting 1356. Sort Integers by The Number of 1 Bits ¶ Time: O(sort)O(\texttt{sort})O(sort) Space: O(n)O(n)O(n) C++JavaPython 1 2 3 4 5 6 7 8 9 10class Solution { public: vector<int> sortByBits(vector<int>& arr) { ranges::sort(arr, ranges::less{}, [](const int a) { const int bitCount = bitset<32>(a).count(); return pair<int, int>{bitCount, a}; }); return arr; } }; 1 2 3 4 5 6 7class Solution { public int[] sortByBits(int[] arr) { Integer[] boxedArr = Arrays.stream(arr).boxed().toArray(Integer[] ::new); Arrays.sort(boxedArr, Comparator.comparingInt(Integer::bitCount).thenComparingInt(a -> a)); return Arrays.stream(boxedArr).mapToInt(Integer::intValue).toArray(); } } 1 2 3class Solution: def sortByBits(self, arr: list[int]) -> list[int]: return sorted(arr, key=lambda x: (x.bit_count(), x)) Was this page helpful? Thanks for your feedback! Thanks for your feedback! Help us improve this page by using our feedback form.