Sort Array by Increasing Frequency (LeetCode 1636): Solution and Explanation
Reorder nums so that rarer values come first, and among values that appear equally often, larger values come first.
Intuition
The order is decided by two things: how often a value appears, and the value itself. Neither can be read off a single element, so first count every value.
Once the counts are known, the rule becomes a sort key. Compare counts first (smaller first), and when counts tie compare values (larger first).
In Python that is the key (count[x], -x). In other languages it is a comparator that checks counts, then falls back to b - a.
Approach: Count, then sort by (count, -value)
- Build a map
countfrom each value to how many times it appears. - Sort
numswith the key(count[x], -x), or a comparator returningcount[a] - count[b]when counts differ andb - aotherwise. - Return the sorted array.
Step-by-step example
nums = [2,3,1,3,2]
- Counts: 2 appears 2 times, 3 appears 2 times, 1 appears once.
- 1 has the smallest count, so it goes first.
- 2 and 3 tie at 2, so the larger value 3 goes before 2.
- Result: [1,3,3,2,2].
Code: Python, Java, C++
1class Solution:
2 def frequencySort(self, nums: List[int]) -> List[int]:
3 count = {}
4 for x in nums:
5 count[x] = count.get(x, 0) + 1
6 nums.sort(key=lambda x: (count[x], -x))
7 return nums1class Solution {
2 public int[] frequencySort(int[] nums) {
3 Map<Integer, Integer> count = new HashMap<>();
4 for (int x : nums) {
5 count.merge(x, 1, Integer::sum);
6 }
7 Integer[] boxed = Arrays.stream(nums).boxed().toArray(Integer[]::new);
8 Arrays.sort(boxed, (a, b) -> count.get(a).equals(count.get(b)) ? b - a : count.get(a) - count.get(b));
9 return Arrays.stream(boxed).mapToInt(Integer::intValue).toArray();
10 }
11}1class Solution {
2public:
3 vector<int> frequencySort(vector<int>& nums) {
4 unordered_map<int, int> count;
5 for (int x : nums) {
6 count[x]++;
7 }
8 sort(nums.begin(), nums.end(), [&](int a, int b) {
9 return count[a] != count[b] ? count[a] < count[b] : a > b;
10 });
11 return nums;
12 }
13};Time and space complexity
O(n log n)
Counting is O(n); the sort dominates.
O(n)
The count map holds up to n distinct values.
Other approaches
Bucket by count (time O(n + V * maxFreq) where V = 201, space O(V))
Values are limited to [-100, 100], so count into a 201-slot array, then for each frequency from 1 upward, walk values from 100 down and write those with that count. No comparison sort needed.
Common mistakes
- Breaking ties in ascending order. The problem asks for the larger value first when counts are equal.
- Sorting the distinct values and forgetting to repeat each one count times in the output.
- In Java, Arrays.sort with a comparator needs Integer[], not int[], so box the array first.
Frequently asked questions
Why sort by -x instead of reversing?
Reversing would also flip the count order. Negating only the value keeps counts ascending while making the tie-break descending.
Is the sort stable enough?
Stability does not matter here. Two elements that compare equal have the same count and the same value, so they are identical.
How is this different from Sort Characters By Frequency?
That problem puts the most frequent characters first and allows any tie order. This one puts the least frequent first and fixes the tie order.