Show problems as
Classic problem #1636EasyArrayHash TableSorting

Sort Array by Increasing Frequency

Real-world version: Order Readings by Repeat Count
Tracked in this browser only
Read Sort Array by Increasing Frequency on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A calibration rig logs temperature drifts into nums, where a drift may be negative, zero or positive and the same drift may be logged many times.

Rearrange the whole log so that a drift logged fewer times stands ahead of a drift logged more times. When two drifts were logged the same number of times, the larger drift comes first. Each drift must still appear exactly as many times as it did in the input, and all copies of one drift sit together.

Return the rearranged log.

Examples

Example 1

Input
nums = [4, -2, 4, -2, 9]
Output
[9, 4, 4, -2, -2]

9 was logged once, 4 twice and -2 twice. The single 9 leads, then the two drifts tied on two logs each appear larger first, so both 4s precede both -2s.

Example 2

Input
nums = [-100, 100, -100, 100, -100, 3]
Output
[3, 100, 100, -100, -100, -100]

3 was logged once, 100 twice and -100 three times, so the groups come out in that order of tally.

Example 3

Input
nums = [6, 6, 2, 2, 9, 9]
Output
[9, 9, 6, 6, 2, 2]

All three drifts were logged twice, so the tie rule alone decides and they come out from largest to smallest.

Constraints

  • 1 <= nums.length <= 100
  • -100 <= nums[i] <= 100

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def frequency_sort(nums: list[int]) -> list[int]:
Java
public int[] frequencySort(int[] nums)