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; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter