Sort Array by Increasing Frequency
Given an array of integers, sort in increasing order based on frequency of values. If multiple values have the same frequency, sort them in decreasing order.
Count frequencies with a hash map, then apply a custom comparator that sorts by frequency ascending then by value descending for ties. This is a two-step sorting approach: first aggregate frequencies, then apply custom comparison during sorting.
Time is O(n log n) dominated by sorting, space O(n) for the frequency map. Edge cases include empty array (return []), single element, and all values having the same frequency (sorted by value descending).
The comparator pattern used here is common in problems requiring custom sort orders. The key is mapping each element to its derived sort key and then applying language-specific sorting with a custom function.
For ties at the same frequency (like -1 and 4 both appearing twice), sorting by decreasing value means larger values appear first (4 before -1). This secondary sorting ensures a deterministic total order when primary sort keys are equal.
This problem is a variation of the frequency sort pattern where the sort order depends on aggregate properties of each distinct value rather than on the values themselves.
Example Input & Output
1 freq 1, 2 and 3 freq 2, 3>2.
1 freq 2, 2 freq 3, 3 freq 1.
Empty.
5 freq 1, -1 freq 2, 4 freq 2. Tie: 4 > -1.
All same.
Algorithm Flow
Solution Approach
Count the frequency of each element using a hash map, then sort the array based on those frequencies in ascending order. Elements with the same frequency maintain their relative order.
Build a frequency map where keys are numbers and values are their occurrence counts. Then use a custom sort comparator that first compares by frequency (ascending), and ties are broken by the number value itself (ascending).
Time complexity is O(n log n) for sorting, space complexity is O(n) for the frequency map.
Best Answers
import java.util.*;
class Solution {
public int[] solution(int[] nums) {
Map<Integer,Integer> f=new HashMap<>();
for (int n:nums) f.put(n,f.getOrDefault(n,0)+1);
Integer[] boxed=Arrays.stream(nums).boxed().toArray(Integer[]::new);
Arrays.sort(boxed,(a,b)->{
int fa=f.get(a),fb=f.get(b);
if (fa!=fb) return fa-fb;
return b-a;
});
return Arrays.stream(boxed).mapToInt(i->i).toArray();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
