Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Thursday, April 23, 2020

Group Anagrams Together java solution


Problem :


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”, “odg”, “act”}, then grouped anagrams are “(dog, odg) (cat, tac, act)”. So the output will be 2 3.

Solution : 

So Problem is to figure out number of occurrence of characters and if there is a repeat then treat it as its anagram.
Ex  ; dog and gdo has same character occurrence so they are anagram.

Here we are going to find unique character occurrence by finding hash of the string's chars and assign this unique hash to map and increment count.

Return the sorted count.


Code : 

 public static String getHash(String cur) { // get Hash for characters of string
         char hash[]=new char[256];
         for(int i=0;i<cur.length();++i){
             char c = cur.charAt(i);
             hash[(int)(c)] = '1';
         }
         return new String(hash);
     }
     public static void fn(String a[],int n)
     {
         Map<String,Integer> hash = new HashMap<>();
         for(String cur: a) {
             String hashKey = getHash(cur);
                 hash.put(hashKey,hash.getOrDefault(hashKey,0)+1);
         }
         List<Integer> list = new ArrayList<>();
         for(Map.Entry<String,Integer> entry : hash.entrySet()) {
             list.add(entry.getValue());
         }
         Collections.sort(list);
         for(int cur:list) {
             System.out.print(cur+" ");
         }
     }

0 Comments:

Post a Comment

Stats