Sort by Number of Set Bits
Sort the non-negative integers in nums by how many 1 bits their binary form has, fewest first. Numbers with the same bit count are ordered by value, smallest first. Return the sorted array.
Example 1
Input: nums = [0, 1, 2, 3, 4, 5, 6, 7, 8] Output: [0, 1, 2, 4, 8, 3, 5, 6, 7]
Example 2
Input: nums = [15, 8, 9] Output: [8, 9, 15]
Constraints
- 0 <= nums.length <= 10^4
- 0 <= nums[i] <= 10^6
Hint 1
Write a comparator that compares bit counts first and values second.
Hint 2
Precompute each bit count once instead of inside the comparator.
Good practice for: Embedded Systems Engineer, Game Developer, Backend Developer, Blockchain Developer, Automation Test Engineer
Run checks your code on 2 sample tests. Submit runs all 7 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.