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.
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 bit_count_buckets = [[] for _ in range(9)]
10 for num in nums:
11 bit_count_buckets[count_set_bits(num)].append(num)
12 for bucket in bit_count_buckets:
13 bucket.sort()
14 sorted_array = [num for bucket in bit_count_buckets for num in bucket]
15 return sorted_array == sorted(nums)
16
17nums = [8, 4, 2, 30, 15]
18print(can_be_sorted(nums))
Python's list of lists serves a similar purpose to an array of lists in other languages. We categorize numbers by set-bit count, sort each category, concatenate them, and verify if the concatenated array is fully sorted.
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.