Find if Array Can Be Sorted - Problem
Can you sort by bit count? You're given an array of positive integers, and you have a special sorting power: you can swap any two adjacent elements if they have the same number of set bits (1s in their binary representation).
Your mission is to determine if you can use this power to sort the entire array in ascending order. You can perform as many swaps as needed, but remember - only adjacent elements with the same bit count can be swapped!
For example, numbers 3 (binary:
Your mission is to determine if you can use this power to sort the entire array in ascending order. You can perform as many swaps as needed, but remember - only adjacent elements with the same bit count can be swapped!
For example, numbers 3 (binary:
11) and 6 (binary: 110) both have 2 set bits, so they can be swapped if they're adjacent. But 3 and 4 (binary: 100) cannot be swapped since they have different bit counts (2 vs 1). Input & Output
example_1.py โ Basic Sortable Case
$
Input:
[8, 4, 2, 1, 3, 5]
โบ
Output:
true
๐ก Note:
We can sort this array by swapping adjacent elements with the same bit count. 8,4,2,1 all have 1 set bit and can be rearranged among themselves. 3,5 have 2 set bits and can be rearranged. Final order: [1,2,3,4,5,8] is achievable.
example_2.py โ Non-Sortable Case
$
Input:
[1, 2, 3, 4, 5]
โบ
Output:
false
๐ก Note:
Looking at bit counts: 1(1bit), 2(1bit), 3(2bits), 4(1bit), 5(2bits). To be sorted, we need 3 to come before 4, but they have different bit counts and can never be swapped. The array cannot be sorted.
example_3.py โ Single Element
$
Input:
[1]
โบ
Output:
true
๐ก Note:
A single element array is always sorted, regardless of bit counts.
Constraints
- 1 โค nums.length โค 100
- 1 โค nums[i] โค 28
- All integers in nums are positive
Visualization
Tap to expand
Understanding the Visualization
1
Identify Bit Groups
Count set bits for each number - this determines their 'color'
2
Group Elements
Organize elements into groups by bit count - same color balls together
3
Sort Within Groups
Sort each color group individually - these represent possible arrangements
4
Verify Global Order
Check if the group arrangement can produce the target sorted sequence
Key Takeaway
๐ฏ Key Insight: Elements can only move within their bit-count groups, so we verify if each group can supply the right elements in the right order for the sorted sequence
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code