TRT
Sign in
easyCoreLeetCode#composite key#counting

Sort array by increasing frequency

Sort values by how often they occur, breaking ties by value in decreasing order, with a composite sort key.

The Runtime Theory Team1 min read
Taught inStability and what libraries usePro — members onlyA stable sort keeps equal elements in their original order, which is what makes sorting by several keys work. Here is which library sorts are stable, what algorithms they really are, and how to write comparators that don't break them.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innums = [1, 1, 2, 2, 2, 3]

out[3, 1, 1, 2, 2, 2]

innums = [2, 3, 1, 3, 2]

out[1, 3, 3, 2, 2]

innums = [-1, 1, -6, 4, 5, -6, 1, 4, 1]

out[5, -1, 4, 4, -6, -6, 1, 1, 1]

Sort an array of integers by the frequency of each value, least frequent first. When two values have the same frequency, put the larger value first.

Before you code

This is a sort by two keys: frequency ascending, then value descending. Count first, then express both keys in one sort.

Hints

  1. Count each value with a hash map.
  2. Sort with the key (count[x], -x): the first component orders by frequency, and the negated value breaks ties in decreasing order.
  3. Alternatively, sort twice with a stable sort: first by value descending, then by frequency. Why must the first sort be the tie-breaker?

Production & complexity notes

When solving Sort array by increasing frequency on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Stability and what libraries use to reinforce the underlying pattern.

What it practices

Multi-key sorting, with a composite key or with stable passes, from Stability and what libraries use.

Not started

Sign in to save your learning progress.

Sign in to save