Sort Integers by The Number of 1 Bits — LeetCode #1356 (Easy)
Tags: Array, Bit Manipulation, Sorting, Counting
Related patterns: Hash Map, Array
Brute Force approach
Time complexity: O(n²). Space complexity: O(1).
The brute-force approach involves counting the number of 1's in the binary representation of each integer and then sorting the array based on these counts. If two integers have the same count, we sort them by their value.
The time complexity is O(n²) because we are sorting the array, and the sorting algorithm can take O(n log n) time. However, counting the bits for each element takes O(n) in the worst case, leading to an overall complexity of O(n²) when considering the sorting.
- Step 1: Create a helper function to count the number of 1's in the binary representation of a number.
- Step 2: For each integer in the array, use the helper function to get the count of 1's.
- Step 3: Sort the array first by the count of 1's and then by the integer value in case of ties.
1. Input: [0,1,2,3,4,5,6,7,8]
2. Count of 1's: [0, 1, 1, 2, 1, 2, 2, 3, 1]
3. Pairing counts with values: [(0,0), (1,1), (1,2), (2,3), (1,4), (2,5), (2,6), (3,7), (1,8)]
4. Sort by counts and values: [(0,0), (1,1), (1,2), (1,4), (1,8), (2,3), (2,5), (2,6), (3,7)]
5. Output: [0,1,2,4,8,3,5,6,7]
Optimal Solution approach
Time complexity: O(n log n). Space complexity: 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.
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.
- Step 1: Use a sorting function that allows custom keys.
- Step 2: For each integer, calculate the number of 1's in its binary representation.
- Step 3: Sort the array using a tuple of (count of 1's, integer value) as the key.
1. Input: [0,1,2,3,4,5,6,7,8]
2. Count of 1's: [0, 1, 1, 2, 1, 2, 2, 3, 1]
3. Pairing counts with values: [(0,0), (1,1), (1,2), (2,3), (1,4), (2,5), (2,6), (3,7), (1,8)]
4. Sort by counts and values: [(0,0), (1,1), (1,2), (1,4), (1,8), (2,3), (2,5), (2,6), (3,7)]
5. Output: [0,1,2,4,8,3,5,6,7]
Key Insights
- Understanding binary representation is crucial for bit manipulation problems.
- Sorting by multiple criteria can be efficiently handled using custom sorting keys.
Common Mistakes
- Not considering the case where multiple integers have the same number of 1's.
- Overcomplicating the sorting logic instead of using built-in functions.
Interview Tips
- Always clarify the sorting criteria with the interviewer.
- Think about edge cases, such as all numbers being the same or having the same number of 1's.
- Practice counting bits using different methods to be comfortable with bit manipulation.