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.
1function countSetBits(n) {
2 let count = 0;
3 while (n) {
4 n &= (n - 1);
5 count++;
6 }
7 return count;
8}
9
10function canBeSorted(nums) {
11 const bitCountBuckets = Array.from({ length: 9 }, () => []);
12 for (let num of nums) {
13 bitCountBuckets[countSetBits(num)].push(num);
14 }
15 for (let bucket of bitCountBuckets) {
16 bucket.sort((a, b) => a - b);
17 }
18 const sortedArray = bitCountBuckets.flat();
19 return sortedArray.every((val, i, arr) => i === 0 || arr[i - 1] <= val);
20}
21
22const nums = [8, 4, 2, 30, 15];
23console.log(canBeSorted(nums));
JavaScript uses arrays to manage each category of numbers by set-bit count. Categories are sorted and reassembled in allowed order to verify overall sorting.
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).
1
By grouping in buckets and simulating as many allowed swaps as necessary within the grouping paradigm, we achieve a checkpoint against the globally sorted version.