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
Find if Array Can Be Sorted INPUT nums = [8, 4, 2, 30, 15] 8 4 2 30 15 Set Bits Count: 1 1 1 4 4 Binary: 1000 100 10 11110 1111 Groups by Set Bits: Group 1: 8,4,2 Group 4: 30,15 ALGORITHM STEPS 1 Count Set Bits For each number, count 1s in binary form 2 Group by Bits Adjacent elements with same bits form groups 3 Sort Within Groups Elements in same group can be freely swapped 4 Check Order Verify max of group i is less than min of group i+1 Group 1: [8,4,2] --> [2,4,8] max=8 Group 4: [30,15] --> [15,30] min=15, 8 < 15 OK FINAL RESULT Sorted Array: 2 4 8 15 30 Output: true Array CAN be sorted! Verification: 1. Group [8,4,2] sorted: [2,4,8] 2. Group [30,15] sorted: [15,30] 3. max(Group1) = 8 4. min(Group2) = 15 5. 8 < 15 ... OK! Key Insight: Elements with the same number of set bits can be swapped freely through adjacent swaps. We only need to check if the maximum of each group is less than the minimum of the next group. If this condition holds for all adjacent groups, the array can be sorted. Time: O(n), Space: O(1). TutorialsPoint - Find if Array Can Be Sorted | Bit Count Grouping
Asked in
Google 12 Microsoft 8
8.5K Views
Medium Frequency
~15 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen