#1356

Sort Integers by The Number of 1 Bits

Easy
ArrayBit ManipulationSortingCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution leverages built-in sorting functions that can handle custom sorting criteria efficiently. By using a tuple of (number of 1's, value) as the sorting key, we can achieve the desired order in a single pass.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a sorting function that allows custom keys.
  2. 2Step 2: For each integer, calculate the number of 1's in its binary representation.
  3. 3Step 3: Sort the array using a tuple of (count of 1's, integer value) as the key.
solution.py8 lines
1# Full working Python code
2
3def sortByBits(arr):
4    return sorted(arr, key=lambda x: (bin(x).count('1'), x))
5
6# Example usage
7arr = [0,1,2,3,4,5,6,7,8]
8print(sortByBits(arr))

Complexity note: The optimal solution has a time complexity of O(n log n) due to the sorting step. The space complexity is O(n) because we create a new sorted array.

  • 1Understanding binary representation is crucial for bit manipulation problems.
  • 2Sorting by multiple criteria can be efficiently handled using custom sorting keys.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.