class Solution { public List> groupAnagrams(String[] strs) { List> result = new ArrayList<>(); Map> map = new HashMap<>(); // iterating over each string from giver array of strings for(String str : strs) { // convert the current string to charArray, and store hash values // suppose str is : "cat" int[] count = new int[26]; for(char ch : str.toCharArray()) { count[ch - 'a']++; } // count[0]=1 --> for 'a', count[2]=1 --> for 'c', count[19]=1 --> for 't' // convert count array into string StringBuilder sb = new StringBuilder(); for(int index : count) { // adding hashes in between the count of characters sb.append("#").append(index); } // sb: "#1#0#1#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#1#0#0#0#0#0#0" // convert string builder to string String key = sb.toString(); // key = "#1#0#1#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#0#1#0#0#0#0#0#0" if(!map.containsKey(key)) map.put(key, new ArrayList()); // Always add the string to the list, whether the key is new or not. // so suppose this key : {cat, act}, adding current string as anagram map.get(key).add(str); } result.addAll(map.values()); return result; } }