49. Group Anagrams

{
    "a1b1t1": ["bat"],
    "a1n1t1": ["nat","tan"],
    "a1e1t1": ["ate","eat","tea"],
}
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs)
    {
        unordered_map<string, vector<string>> m;

        for(auto& s : strs)
        {
            vector<int> freq(26);
            for(auto& c : s) ++freq[c - 'a'];

            string t;
            for(int i = 0; i < 26; ++i)
            {
                if (!freq[i]) continue;
                t += string(1, i + 'a');
                t += to_string(freq[i]);
            }
            m[t].push_back(s);
        }

        vector<vector<string>> res;
        for(auto& a : m) res.push_back(a.second);
        return res;
    }
};
  • T: O(NK)O(N \cdot K)
  • S: O(NK)O(N \cdot K)