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).
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 sortedNums = [...nums].sort((a, b) => a - b);
12 const bitCountBuckets = Array.from({ length: 9 }, () => []);
13 nums.forEach(num => {
14 bitCountBuckets[countSetBits(num)].push(num);
15 });
16 bitCountBuckets.forEach(bucket => bucket.sort((a, b) => a - b));
17 let index = 0;
18 for (let bucket of bitCountBuckets) {
19 for (let num of bucket) {
20 if (sortedNums[index++] !== num) return false;
21 }
22 }
23 return true;
24}
25
26const nums = [8, 4, 2, 30, 15];
27console.log(canBeSorted(nums));JS facilitation of original to sorted data map support and confirmation against individual set bit group sortings finds operational efficiencies.
Solve with full IDE support and test cases