Find if Array Can Be Sorted

Medium Topics Company Tags

You may swap two adjacent entries of nums only when their binary representations contain the same number of 1 bits. Return true if some sequence of these swaps can put the array in non-decreasing order, or false otherwise. You may use zero swaps.

Example 1:

Input: nums = [4,2,1]

Output: true

Explanation: Each value has exactly one set bit. Swap adjacent entries to obtain [1,2,4], which is sorted.

Example 2:

Input: nums = [3,2]

Output: false

Explanation: The values 3 and 2 have two and one set bits respectively, so they cannot be swapped. Their decreasing order cannot be fixed.

Example 3:

Input: nums = [2,3]

Output: true

Explanation: The array is already sorted, so it needs no swaps even though the entries have different set-bit counts.

Constraints:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 256


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.