Sort Integers by The Number of 1 Bits — LeetCode 1356 Python Solution
- Problem
- #1356
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
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
class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
return sorted(arr, key=lambda x: (x.bit_count(), x))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \log n) |
| Space | O(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.