Find if Array Can Be Sorted - Problem
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.
Input & Output
Example 1 — Basic Sortable Case
$
Input:
nums = [8,4,2,30,15]
›
Output:
true
💡 Note:
Elements 8,4,2 have 1 set bit each and can be sorted among themselves. Elements 30,15 have 4 and 4 set bits respectively and can be arranged. The array can become [2,4,8,15,30].
Example 2 — Non-sortable Case
$
Input:
nums = [1,2,3,4,5]
›
Output:
false
💡 Note:
Each element has different number of set bits: 1(1), 2(1), 3(2), 4(1), 5(2). Cannot swap 3 and 4 since they have different bit counts, so array cannot be fully sorted.
Example 3 — Already Sorted
$
Input:
nums = [3,16,8,4,2]
›
Output:
false
💡 Note:
16 has 1 set bit, but 3 has 2 set bits. Since they have different bit counts, 16 cannot move to the beginning to achieve sorted order [2,3,4,8,16].
Constraints
- 1 ≤ nums.length ≤ 100
- 1 ≤ nums[i] ≤ 28
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Count set bits for each element: [8→1, 4→1, 2→1, 30→4, 15→4]
2
Grouping
Group by bit count: Group1=[8,4,2] (1 bit), Group2=[30,15] (4 bits)
3
Verification
Check if each group can be sorted to match target positions
Key Takeaway
🎯 Key Insight: Elements can only swap with adjacent elements having the same number of set bits, creating sortable groups
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code