Given an array of integers, your task is to rearrange the elements based on how many 1s appear in their binary form.
The sorting must follow these rules:
Numbers with fewer 1-bits should appear earlier.
If two values contain the same number of 1-bits, sort them by their natural ascending order.
Return the final sorted array.
Input: arr = [5, 3, 9, 6]
Output: [3, 5, 6, 9]
Explanation:
Binary forms: 5 → 101 (2 ones) 3 → 011 (2 ones) 9 → 1001 (2 ones) 6 → 110 (2 ones) All have equal bit-count → sort normally.
Input: arr = [7, 8, 1, 2]
Output: [1, 2, 8, 7]
Explanation:
Binary: 7 → 111 (3 ones) 8 → 1000 (1 one) 1 → 1 (1 one) 2 → 10 (1 one) 1-bit group → [1, 2, 8] (sorted) 3-bit group → [7]
Accepted:
Submission: