Problem 316504 · medium · Level 03 Linear Management & Searching

Order by Rarity

sorting · Counter · multi-key sort

Given a list of integers nums, return a new list with the same elements ordered by how often each value occurs: rarer values first. When two values occur the same number of times, the larger value comes first.

Examples

Input:  nums = [7, 4, 7, 9, 4, 7]
Output: [9, 4, 4, 7, 7, 7]
Explanation: 9 occurs once, 4 twice, 7 three times.
Input:  nums = [5, 8, 6, 8, 5]
Output: [6, 8, 8, 5, 5]
Explanation: 5 and 8 both occur twice, so the larger value 8 comes first.

Constraints

  • 0 <= len(nums) <= 10**5
  • -10**9 <= nums[i] <= 10**9
  • Target complexity: O(n log n).

Goals

  • Count frequencies before sorting
  • Use the frequency as the primary key and the value as a descending tie-breaker
  • Keep every occurrence of each value in the output
Starting Python…