Editor

Sort by Frequency

#75 · Sorting and searching · Intermediate · 65 XP · about 10 min

Write sort_by_frequency(nums) that returns a new list holding the same numbers, arranged so the values that appear most often come first. Copies of a value stay together. When two values appear the same number of times, the smaller value comes first.

Examples

sort_by_frequency([4, 6, 2, 6, 4, 6])   # returns [6, 6, 6, 4, 4, 2]
sort_by_frequency([3, 1, 3, 1, 2])      # returns [1, 1, 3, 3, 2]
sort_by_frequency([5, -1, 5, -1, 0])    # returns [-1, -1, 5, 5, 0]

In the second example, 1 and 3 both appear twice, so the smaller one, 1, goes first; 2 appears once and comes last.

Constraints

  • 0 <= len(nums) <= 10,000
  • -10^6 <= nums[i] <= 10^6

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.