Sponsored
Sponsored
This approach involves creating a mapping of numbers based on their set bits count. We group all numbers having the same set bits count and sort each group individually. If by concatenating these sorted groups in the order of their set bits count, we can get a sorted version of the original array, then we return true; otherwise, return false.
Time Complexity: O(n log n), primarily due to the sorting step for each bucket.
Space Complexity: O(n), for the additional storage required for the bitCountBuckets.
The implementation first calculates the number of set bits for each element in the array. We then utilize arrays akin to buckets to store elements based on their set bits count. Each bucket is then independently sorted. Finally, the sorted buckets are concatenated and checked for any overall sorting errors.
In this approach, we simulate the individual moves as described in the problem. We group numbers by their set bit counts and within each group, attempt sorting by simulating adjacent swaps. Finally, we attempt confirmation by juxtaposing against a globally sorted array.
Time Complexity: O(n log n), due to multiple sorting.
Space Complexity: O(n).
1import java.util.ArrayList;
2import java.util.Arrays;
3import java.util.Collections;
4import java.util.List;
5
6public class SortableArrayChecker {
7
8 public static int countSetBits(int n) {
9 int count = 0;
10 while (n != 0) {
11 n &= (n - 1);
12 count++;
13 }
14 return count;
15 }
16
17 public static boolean canBeSorted(int[] nums) {
18 int[] sortedNums = nums.clone();
19 Arrays.sort(sortedNums);
20 List<Integer>[] bitCountBuckets = new ArrayList[9];
21 for (int i = 0; i <= 8; i++) {
22 bitCountBuckets[i] = new ArrayList<>();
23 }
24 for (int num : nums) {
25 bitCountBuckets[countSetBits(num)].add(num);
26 }
27 for (List<Integer> bucket : bitCountBuckets) {
28 Collections.sort(bucket);
29 }
30
31 int index = 0;
32 for (List<Integer> bucket : bitCountBuckets) {
33 for (int num : bucket) {
34 if (sortedNums[index++] != num) return false;
35 }
36 }
37 return true;
38 }
39
40 public static void main(String[] args) {
41 int[] nums = {8, 4, 2, 30, 15};
42 System.out.println(canBeSorted(nums));
43 }
44}This Java variant balances sorting individual bit groupings followed by combining and checking against a conventional sort iteration of the original data.
Solve with full IDE support and test cases