Skip to content
BytePatterns

Sort by Equal-Bit Swaps

MediumBit Manipulation#popcount#adjacent-swaps~25m

Problem

You may swap two neighbouring elements of a list, as often as you like, but only when both have the same number of 1 bits in binary. Given a list of non-negative whole numbers, return True if these swaps can sort it into ascending order, and False otherwise.

Examples

Input:  nums = [6, 5, 3, 16, 8, 31]
Output: True
Why:    6, 5, 3 all have two 1 bits and sort to 3, 5, 6; 16 and 8 have one and sort to 8, 16
Input:  nums = [6, 3, 1, 4, 2]
Output: False
Why:    6 has two 1 bits, 1 has one, so 1 can never get past 6
Input:  nums = [7]
Output: True
Why:    edge case, a single value is already sorted

Hints

0 / 3

Stuck on the idea rather than the code? Bubble Sort covers it.