Ctrl K

Order by Set Bits

Easy
You are given an array values of non-negative integers. Sort it by how many 1s each number has in binary, with the fewest first. If two numbers have the same number of 1s, the smaller number comes first. Return the sorted array.
Example 1
values=[10, 7, 4, 3, 16] → [4, 16, 3, 10, 7]

In binary 4 = 100 and 16 = 10000 have one 1 each, 10 = 1010 and 3 = 11 have two, and 7 = 111 has three. Inside each group the numbers go in ascending order: [4, 16, 3, 10, 7].

Example 2
values=[5, 0, 6, 5] → [0, 5, 5, 6]

0 has no 1s, while 5 = 101 and 6 = 110 both have two.

Constraints
  • 1 ≤ len(values) ≤ 500
  • 0 ≤ values[i] ≤ 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsThe Candidate With Most Votes EasyThe Lost Ticket EasyValues One Apart EasyDoubled Tag, Lost Tag EasyWords From Working Keys Easy
loading Python…
Input
values=[10, 7, 4, 3, 16]
Expected
[4, 16, 3, 10, 7]

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