Given an array of non-negative integers arr, sort the array in descending order of the number of set bits (1-bits) in each integer's binary representation.
If two integers have the same number of set bits, keep their relative order from the input (a stable sort). Return the sorted array.
Function Signature
def sort_by_set_bits(arr: list[int]) -> list[int]:
Rules
-
The set-bit count of a value is the number of 1 digits in its binary form. For example, 7 is
111
in binary (3 set bits) and 8 is
1000
(1 set bit).
-
Values with more set bits come first.
-
Values with the same set-bit count appear in the same relative order as in
arr
. Repeated values are all kept.
-
Return a list with the same length as
arr
.
Constraints
-
1 <= len(arr) <= 10^4
-
0 <= arr[i] <= 10^9
Examples
Input: arr = [7,1,3,8,15,2]
Output: [15,7,3,1,8,2]
In binary, 15 is 1111 (4 set bits), 7 is 111 (3) and 3 is 11 (2), while 1, 8 and 2 have one set bit each. Those three tie, so they keep their input order: 1, 8, 2.
Input: arr = [0,1,2,3,4,5,6,7]
Output: [7,3,5,6,1,2,4,0]
7 has three set bits, 3, 5 and 6 have two, 1, 2 and 4 have one, and 0 has none. Inside each group the values stay in the order they had in the input.