You are given a 0-indexed array of positive integers nums
.
In one operation, you can swap any two adjacent elements if they have the same number of set bits. You are allowed to do this operation any number of times (including zero).
Return true
if you can sort the array in ascending order, else return false
.
Example 1:
Input: nums = [8,4,2,30,15]
Output: true
Example 2:
Input: nums = [1,2,3,4,5]
Output: true
Example 3:
Input: nums = [3,16,8,4,2]
Output: false
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 2^8
def can_sort_array(nums):
"""Determines if an array can be sorted by swapping adjacent elements with the same number of set bits."""
n = len(nums)
arr = [(bin(num).count('1'), num) for num in nums]
for i in range(n):
for j in range(n - i - 1):
if arr[j][0] == arr[j+1][0] and arr[j][1] > arr[j+1][1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
sorted_nums = [num for _, num in arr]
return sorted_nums == sorted(nums)
# Example Usage:
nums1 = [8, 4, 2, 30, 15]
print(f"Input: {nums1}, Output: {can_sort_array(nums1)}") # Output: True
nums2 = [1, 2, 3, 4, 5]
print(f"Input: {nums2}, Output: {can_sort_array(nums2)}") # Output: True
nums3 = [3, 16, 8, 4, 2]
print(f"Input: {nums3}, Output: {can_sort_array(nums3)}") # Output: False
can_sort_array(nums)
Function:
nums
as input.arr
. This is done using a list comprehension: arr = [(bin(num).count('1'), num) for num in nums]
arr
to get sorted_nums
. Checks if sorted_nums
is equal to the ascending sorted version of original nums
. Returns True
if they are the same, else False
.n
times (where n
is the length of nums
).n
times in the worst case.bin(num).count('1')
is O(1) since the integers are limited to a maximum of 8 bits as per the constraints).arr
list stores tuples containing set bit counts and original numbers, using O(n) space.sorted_nums
also requires O(n) space to store the sorted numbers.Empty Input:
nums
is empty, the function will still work correctly because the loops won't execute, and it will return True
(since an empty list is considered sorted).Already Sorted Array:
True
efficiently.Array with Identical Elements:
[2, 2, 2, 2]
), the function will also return True
because it's already considered sorted.Array with Numbers Having Same Number of Set Bits but Cannot Be Sorted:
[3, 16, 8, 4, 2]
. 3 has two set bits, 16, 8, 4, and 2 have one set bit. Numbers with one set bit can be rearranged between each other. The algorithm will correctly return False
because even after optimally rearranging the numbers with one set bit, we can't sort the array.Large Input Array: