Ctrl K

Swap Neighbours With Equal Bits

Medium
You are given a list of positive integers values. In one move you may swap two adjacent elements, but only if their binary forms contain the same number of 1s. You may make any number of moves, including none. Return True if such moves can sort the list in non-decreasing order, and False otherwise.
Example 1
values=[6, 3, 5, 16, 8] → True

6, 3 and 5 each have two 1-bits (110, 11, 101), so they can be rearranged into 3, 5, 6. 16 and 8 each have one 1-bit and can be swapped too, giving [3, 5, 6, 8, 16].

Example 2
values=[4, 3, 8] → False

4 and 3 would have to trade places, but 4 has one 1-bit and 3 has two, so that swap is not allowed.

Example 3
values=[10] → True
Constraints
  • 1 ≤ len(values) ≤ 100
  • 1 ≤ values[i] ≤ 2¹⁶
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsK-th Largest Corner XOR MediumOne New Letter MediumStrongest Product Team MediumThe Lost Ticket EasyDoubled Tag, Lost Tag Easy
loading Python…
Input
values=[6, 3, 5, 16, 8]
Expected
True

Run checks the first 3 tests in your browser. Submit checks all 135 tests on the server, hidden ones included.