#1636

Sort Array by Increasing Frequency

Easy Custom comparator

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Sort numbers by how often they appear (rarest first). When two values are equally frequent, put the larger value first.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: sort by how often each value appears; ties go bigger value first.

Why this works: count with a map, then sort with a two-key comparator.

Example: [2, 3, 1, 3, 2]

freq: 1→1, 2→2, 3→21 first, then 3, 3 before 2, 2 (tie → bigger first)[1, 3, 3, 2, 2]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Trying to pass a comparator to Arrays.sort(int[]) — comparators only work on object arrays.

Solve on LeetCode ↗
Complexity
  • Time: O(n log n).
  • Space: O(n).
Topic: Sorting
🎬 Episodes 24–28: video coming soon