1. class Solution {
  2. public List<List<String>> groupAnagrams(String[] strs) {
  3. List<List<String>> result = new ArrayList<>();
  4.  
  5.  
  6. Map<String, List<String>> map = new HashMap<>();
  7. // iterating over each string from giver array of strings
  8. for(String str : strs)
  9. {
  10. // convert the current string to charArray, and store hash values
  11. // suppose str is : "cat"
  12. int[] count = new int[26];
  13. for(char ch : str.toCharArray())
  14. {
  15. count[ch - 'a']++;
  16. }
  17. // count[0]=1 --> for 'a', count[2]=1 --> for 'c', count[19]=1 --> for 't'
  18.  
  19. // convert count array into string
  20. StringBuilder sb = new StringBuilder();
  21. for(int index : count)
  22. {
  23. // adding hashes in between the count of characters
  24. sb.append("#").append(index);
  25. }
  26. // 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"
  27.  
  28. // convert string builder to string
  29. String key = sb.toString();
  30. // 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"
  31. if(!map.containsKey(key))
  32. map.put(key, new ArrayList<String>());
  33.  
  34. // Always add the string to the list, whether the key is new or not.
  35. // so suppose this key : {cat, act}, adding current string as anagram
  36. map.get(key).add(str);
  37. }
  38.  
  39. result.addAll(map.values());
  40. return result;
  41. }
  42. }