Q24 Group Anagrams - LeetCode

PHOTO EMBED

Thu Jan 26 2023 09:40:47 GMT+0000 (Coordinated Universal Time)

Saved by @Ayush_dabas07

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        //make a HM of < HM<char,int> , ArrayList<String> >
        HashMap< HashMap<Character,Integer> , ArrayList<String>> map = new HashMap<>();

        //traverse and fill the hashmap and group same anagrams together
        for(String temp : strs){

            //make a frequency map of this and add it to out HM
            HashMap<Character,Integer> fmap = new HashMap<>();

            for(int i =0 ;i < temp.length();i++){
                char ch = temp.charAt(i);

                fmap.put(ch , fmap.getOrDefault(ch , 0)+1);
            }

            //now check if the frequency map already exists in our HM 
            //if yes its going to be a group anagram and add it in the group
            //if not make a new list and add it in out HM

            if(map.containsKey(fmap))
                map.get(fmap).add(temp);

            else{
                ArrayList<String> arr = new ArrayList<>();
                arr.add(temp);
                map.put(fmap ,arr);
            }
        }

        //make a answer arraylist and add in the answer arraylist and return
        List<List<String>> ans = new ArrayList<>();

        for(HashMap<Character,Integer> temp : map.keySet()){
            ans.add(map.get(temp));
        }

        return ans;
    }
}






content_copyCOPY

https://leetcode.com/problems/group-anagrams/