β Frequency Sort (Contest)
Frequency Sort easy Time Limit: 2 sec Memory Limit: 128000 kB
```java
import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework
// don't change the name of this class
// you can add inner classes if needed
class Main {
public static void main (String[] args) {
// Your code here
Scanner sc = new Scanner(System.in);
int tc = sc.nextInt();
while(tc-- > 0){
int n = sc.nextInt();
int[] arr = new int[n];
for(int i = 0; i<arr.length ; i++){
arr[i] = sc.nextInt();
}
HashMap <Integer , Integer> hm = new HashMap<>();
for(int num : arr){
hm.put(num , hm.getOrDefault(num , 0)+1);
}
List <Integer>[] bucket = new List[n];
for(int key : hm.keySet()){
int freq = hm.get(key);
if(bucket [freq-1] == null){
bucket[freq-1] = new ArrayList <>();
}
bucket[freq-1].add(key);
}
StringBuilder res = new StringBuilder();
for(int i = n-1 ; i>=0; i--){
if(bucket[i] != null){
Collections.sort(bucket[i]);
for(int num : bucket[i]){
for(int j = 0 ;j<hm.get(num) ; j++){
res.append(num).append(" ");
}
}
}
}
System.out.println(res.toString().trim());
}
sc.close();
}
}
```Last updated