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.
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 List<int>[] bitCountBuckets = new List<int>[9];
18 for (int i = 0; i <= 8; i++) {
19 bitCountBuckets[i] = new List<int>();
20 }
21
22 foreach (int num in nums) {
23 bitCountBuckets[CountSetBits(num)].Add(num);
24 }
25
26 foreach (var bucket in bitCountBuckets) {
27 bucket.Sort();
28 }
29
30 List<int> sortedArray = new List<int>();
31 foreach (var bucket in bitCountBuckets) {
32 sortedArray.AddRange(bucket);
33 }
34
35 for (int i = 0; i < sortedArray.Count - 1; i++) {
36 if (sortedArray[i] > sortedArray[i + 1]) {
37 return false;
38 }
39 }
40
41 return true;
42 }
43
44 static void Main() {
45 int[] nums = {8, 4, 2, 30, 15};
46 Console.WriteLine(CanBeSorted(nums));
47 }
48}
This C# solution implements a form of bucket sorting based on the number of set bits in elements of the array, and checks if ordering is achieved through local 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.