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).
1def count_set_bits(n):
2 count = 0
3 while n:
4 n &= (n - 1)
5 count += 1
6 return count
7
8def can_be_sorted(nums):
9 sorted_nums = sorted(nums)
10 bit_count_buckets = [[] for _ in range(9)]
11 for num in nums:
12 bit_count_buckets[count_set_bits(num)].append(num)
13 for bucket in bit_count_buckets:
14 bucket.sort()
15 index = 0
16 for bucket in bit_count_buckets:
17 for num in bucket:
18 if sorted_nums[index] != num:
19 return False
20 index += 1
21 return True
22
23nums = [8, 4, 2, 30, 15]
24print(can_be_sorted(nums))Packed Python execution places individual bit counts in separate lists, rearranging as enforced by original and sorted vectors.
Solve with full IDE support and test cases