The Find if Array Can Be Sorted interview question asks if you can sort an array by only swapping adjacent elements that have the same number of "set bits" (the number of 1s in their binary representation). You can perform as many swaps as needed. If the array can eventually be made non-decreasing, return true.
This Find if Array Can Be Sorted coding problem is a favorite at Microsoft and Meta. It tests your ability to recognize how local constraints affect global properties. It combines Bit Manipulation with Sorting or Grouping patterns. The key insight is that elements with the same set bit count can be reordered in any way among themselves, acting as a single movable "block."
This problem uses Group-based Sorting Analysis.
Array: [8, 4, 2, 30, 15]
[8, 4, 2]. Min=2, Max=8. (Can be sorted to 2,4,8).[30, 15]. Min=15, Max=30. (Can be sorted to 15,30).Integer.bitCount() or bin(n).count('1').Whenever a problem involves "swapping adjacent elements under condition X," look for invariants. Usually, this means the array is partitioned into segments that can be internally sorted but cannot mix with other segments.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Set Mismatch | Easy | Solve | |
| Sort Integers by The Number of 1 Bits | Easy | Solve | |
| Count Days Without Meetings | Medium | Solve | |
| Single Number III | Medium | Solve | |
| Single Number II | Medium | Solve |