Sort Integers by The Number of 1 Bits

Given an integer array arr, sort it in ascending order by how many 1s each number has in its binary form. Numbers with the same count of 1s are ordered by their value, smallest first. Return the sorted array.

30:00

Sort Integers by The Number of 1 Bits
easy
Free written solution
Topics
Companies

Given an integer array arr, sort it in ascending order by how many 1s each number has in its binary form. Numbers with the same count of 1s are ordered by their value, smallest first. Return the sorted array.

Example 1:
Input: {"arr":[0,1,2,3,4,5,6,7,8]}
Output: [0,1,2,4,8,3,5,6,7]
Constraints:
  • 1≤arr.length≤5001 \leq \text{arr.length} \leq 500

  • 0≤arr[i]≤1040 \leq \text{arr}[i] \leq 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"arr":[0,1,2,3,4,5,6,7,8]}

Order by the count of 1 bits first, and by value when two numbers tie on that count.

Input

0

1

2

3

4

5

6

7

8

Buckets by count of 1 bits

0 ones

empty

1 one

empty

2 ones

empty

3 ones

empty

result

empty until the buckets are poured

Variables
VariableValue
n9
DepthFunction Call
Stack empty
0/17