Leetcode 1356. Sort Integers by The Number of 1 Bits
Given an integer array arr, you need to sort the integers in the array in ascending order by the number of 1s in their binary representation and in case of two or more integers have the same number of 1s you need to sort them in ascending order of their values.
arr = [0,1,2,3,4,5,6,7,8]
[0,1,2,4,8,3,5,6,7]0 -> 00001 -> 00012 -> 00103 -> 00114 -> 01005 -> 01016 -> 01107 -> 01118 -> 10001s gives us [0, 1, 2, 4, 8, 3, 5, 6, 7].arr = [1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]1 bit for each number.1 bits and then by numeric value in case of ties.1 bits.1 bits.Using Java, we will:
1 bits using Integer.bitCount.Arrays.sort with the custom comparator.Arrays.sort() is O(n log n), where n is the number of elements in the array.1 bits using Integer.bitCount is O(1) since it processes a constant number of bits.import java.util.Arrays;
public class Solution {
public int[] sortByBits(int[] arr) {
// Sorting the array with a custom comparator
Arrays.sort(arr, (a, b) -> {
int bitCountA = Integer.bitCount(a);
int bitCountB = Integer.bitCount(b);
if (bitCountA == bitCountB) {
return a - b; // If counts are equal, sort by the numeric value
} else {
return bitCountA - bitCountB; // Else sort by the bit count
}
});
return arr;
}
public static void main(String[] args) {
Solution sol = new Solution();
// Test cases
int[] arr1 = {0,1,2,3,4,5,6,7,8};
System.out.println(Arrays.toString(sol.sortByBits(arr1))); // [0, 1, 2, 4, 8, 3, 5, 6, 7]
int[] arr2 = {1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1};
System.out.println(Arrays.toString(sol.sortByBits(arr2))); // [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?