Given an array of words, print the count of all anagrams together in sorted order (increasing order of counts). For example, if the given array is {“cat”, “dog”, “tac”, “god”, “act”}, then grouped anagrams are “(dog, god) (cat, tac, act)”. So the output will be 2 3.
Input:
First line consists of T test case. First line of every test case consists of N, denoting the number of words in array. Second line of every test case consists of words of array.
Output:
Single line output, print the counts of anagrams in increasing order.
Constraints:
1<=T<=100 1<=N<=50
Example:
Input:
2
5
act cat tac god dog
3 act cat tac
Output:
2 3
3
My approach:
/*package whatever //do not write package name here */
import java.util.Scanner;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collections;
import java.lang.StringBuffer;
class GFG {
private static void getAnagramCt (String[] words) {
HashMap <String, Integer> anag = new HashMap<>();
List<Integer> counts = new ArrayList<> ();
Set<String> keys;
String[] keyArr;
anag.put(words[0],0);
keys = anag.keySet();
keyArr = keys.toArray(new String[keys.size()]);
for (int i = 1; i < words.length; i++) {
String elem = words[i];
for (int j = 0; j < keyArr.length; j++) {
if (isAnagram(elem,keyArr[j])) {
int ct = anag.get(keyArr[j]);
anag.put(keyArr[j],ct+1);
}
else {
if (j == keyArr.length - 1) {
anag.put(elem, 0);
}
else {
continue;
}
}
}
keys = anag.keySet();
keyArr = keys.toArray(new String[keys.size()]);
}
for (Map.Entry<String,Integer> entry : anag.entrySet()) {
//System.out.println(entry.getKey() + " " + entry.getValue());
counts.add(entry.getValue() + 1);
}
Collections.sort(counts);
for (Integer elem : counts) {
System.out.print(elem + " ");
}
System.out.println();
}
private static boolean isAnagram (String word2, String word1) {
if (word1.length() != word2.length()) {
return false;
}
StringBuffer word = new StringBuffer(word2);
for (int i = 0; i < word1.length(); i++) {
if (word.length() == 0) {
return false;
}
else if (word.indexOf((String.valueOf(word1.charAt(i)))) == -1) {
return false;
}
else {
int ind = word.indexOf((String.valueOf(word1.charAt(i))));
word.deleteCharAt(ind);
}
}
return true;
}
public static void main (String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int numTests = sc.nextInt();
for (int i = 0; i < numTests; i++) {
int numWords = sc.nextInt();
String[] words = new String[numWords];
for (int j = 0; j < numWords; j++) {
words[j] = sc.next();
}
getAnagramCt(words);
}
}
}
I have the following questions with regards to the above code:
How can I further improve my approach?
Is there a better way to solve this question?
Are there any grave code violations that I have committed?
Can space and time complexity be further improved?