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).
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5class SortableArrayChecker {
6
7 public static int CountSetBits(int n) {
8 int count = 0;
9 while (n != 0) {
10 n &= (n - 1);
11 count++;
12 }
13 return count;
14 }
15
16 public static bool CanBeSorted(int[] nums) {
17 int[] sortedNums = (int[])nums.Clone();
18 Array.Sort(sortedNums);
19 List<int>[] bitCountBuckets = new List<int>[9];
20 for (int i = 0; i <= 8; i++) {
21 bitCountBuckets[i] = new List<int>();
22 }
23 foreach (int num in nums) {
24 bitCountBuckets[CountSetBits(num)].Add(num);
25 }
26 foreach (var bucket in bitCountBuckets) {
27 bucket.Sort();
28 }
29
30 int index = 0;
31 foreach (var bucket in bitCountBuckets) {
32 foreach (var num in bucket) {
33 if (sortedNums[index++] != num) return false;
34 }
35 }
36 return true;
37 }
38
39 static void Main() {
40 int[] nums = {8, 4, 2, 30, 15};
41 Console.WriteLine(CanBeSorted(nums));
42 }
43}An evolution of set-bit group checking establishes base correctness srcursed on the sorted numerical set comparisons.
Solve with full IDE support and test cases