Problem 316504 · medium · Phase 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 = [1, 1, 2, 2, 2, 3]
Output: [3, 1, 1, 2, 2, 2]
Explanation: 3 occurs once, 1 twice, 2 three times.
Input:  nums = [2, 3, 1, 3, 2]
Output: [1, 3, 3, 2, 2]
Explanation: 2 and 3 both occur twice, so the larger value 3 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…