Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

Example 2:
Input: strs = [""]
Output: [[""]]

Approach 1
  • Below approach but instead of sorting we store alphabet array
Approach 2
  • Loop over strs and for each string store original in temp and sort the string then use sorted string as key in a map and temp and value
  • Time: O(nlogn) Space: O(n) as sorting would take O(nlogn)
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> anagram;
        vector<vector<string>> ans;
 
        for(string str: strs) {
            string temp = str;
            sort(str.begin(),str.end());
            anagram[str].push_back(temp);
        }
 
        for(const auto& pair: anagram) {
            ans.push_back(pair.second);
        }
 
        return ans;
    }
};
class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        HashMap<String,List<String>> anagram = new HashMap<>();
        List<List<String>> ans = new ArrayList<>();
 
        for(String str: strs) {
            char[] charArray = str.toCharArray();
            Arrays.sort(charArray);
            String key = new String(charArray);
 
            if(!anagram.containsKey(key)) {
                anagram.put(key, new ArrayList<>());
            }
            anagram.get(key).add(str);    
        }
 
        return new ArrayList<>(anagram.values());
    }
}
class Solution {
 
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String,List<String>> res = new HashMap<>();
        for(String str: strs) {
            int[] count = new int[26];
            for(char s: str.toCharArray()) {
                count[s - 'a']++;
            }
            String key = Arrays.toString(count);
            res.putIfAbsent(key,new ArrayList<>());
            res.get(key).add(str);
        }
        return new ArrayList<>(res.values());
    }
}