DSA Factory
Free Mixed sets lessonsMixed sets · Stage 4 · Set 5 · Step 4

Order by a score you compute

Sort numbers by a score that you work out for each one, and break ties with the number itself. About 10 minutes.

Sort by a key

Often the order you want isn't the numbers' own size. Here you must order whole numbers by how many 1s they have when written in binary, and when two numbers have the same count, the smaller number comes first.

Don't write a new sort. Give each number a key, here the pair of its 1-count and its value, and let the sort compare keys. The pair compares the first part first, and only looks at the second part when the first parts are equal.

Key: a score or pair worked out for each item.
Pair key: second part only breaks ties.
In code
nums.sort(key=lambda n: (n % 10, n))
# sorted by the last digit
Sort [6, 9, 2, 7, 12] by number of 1s in binary, then by value.
01234
number
6
9
2
7
12
ones
2
2
1
3
2

Work out each score: 6 is 110 (two 1s), 9 is 1001 (two), 2 is 10 (one), 7 is 111 (three), 12 is 1100 (two).

Move 1 of 4
Quick check

Two numbers have the same number of 1s in binary. How are they ordered?

  1. ABy their own value, smaller first
  2. BBy the order they were given
  3. CIn any order
Show the answer

By their own value, smaller first. That is the second part of the key, used only when the first parts tie.

Your problem

Order by the number of ones

nums is a list of non-negative whole numbers. Sort them by how many 1s each has when written in binary, fewest first. Numbers with the same count are sorted by their own value, smallest first. Return the sorted list.

Example
nums = [5, 3, 7, 8, 1] → [1, 8, 3, 5, 7]

0 ≤ length ≤ 3,000 · 0 ≤ value ≤ 1,000,000,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve