Rarest Values First
Problem
A support team wants to review unusual error codes before common ones. Given the list of logged codes codes, reorder it so that codes appearing fewer times come first.
Codes with the same frequency are ordered by ascending value. Every occurrence stays in the output, and equal codes end up next to each other.
Example 1
- Input:
- codes = [4, 4, 1, 2, 2, 2, 3]
- Output:
- [1, 3, 4, 4, 2, 2, 2]
1 and 3 appear once (ascending: 1, 3), 4 twice, 2 three times.
Example 2
- Input:
- codes = [9, -9, 9, -9, 0]
- Output:
- [0, -9, -9, 9, 9]
Constraints
- 1 ≤ codes.length ≤ 10^5
- -10^4 ≤ codes[i] ≤ 10^4
Hint
Show the first hint
The order of a code depends on how often it appears. Compute that first.
Walkthrough
How to approach it
01Clarify before coding
- Ties in frequency? Ascending by value.
- Should repeated codes be collapsed? No, all occurrences are kept.
- Negative codes? Yes, they sort numerically.
02Brute force
Inside the comparator, count each value's frequency by scanning the whole list.
Cost: O(n² log n): every comparison costs O(n).
The rest of the walkthrough is in the app
The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.
This problem is part of Pro.