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: 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
Bit-Constrained Sorting VisualizationStep 1: Calculate bit counts for each element810001 bit41001 bit3112 bits61102 bitsStep 2: Group by bit count (like grouping by color)1-Bit Group842-Bit Group36Step 3: Sort within each group1-Bit Sorted: [4, 8]482-Bit Sorted: [3, 6]36โœ“ Result: Can achieve [3, 4, 6, 8] - groups provide elements in correct order!Target: [3, 4, 6, 8] โ†’ 2-bit:3, 1-bit:4, 2-bit:6, 1-bit:8 โœ“
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
Asked in
Microsoft 35 Amazon 28 Google 22 Meta 15
28.5K Views
Medium Frequency
~18 min Avg. Time
847 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