49. Group Anagrams

Given an array of strings, group anagrams together.

For example, given:["eat", "tea", "tan", "ate", "nat", "bat"], Return:

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Thoughts:

Pick a "normalized" string as a key to store the family of all the anagrams. Here we can use sorted string as the standard one

Code O(nlogn) with standard sort

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map <string, multiset<string>>mp; // use multiset 
        // to prevent corner case like ["",""]
        for(string s: strs){
            string t = s;
            // "normalize" the string
            sort(t.begin(), t.end());
            mp[t].insert(s);
        }

        vector<vector<string>> anagrams;
        for(auto m: mp){
            vector<string> anagram(m.second.begin(), m.second.end());
            anagrams.push_back(anagram);
        }

        return anagrams;
    }
};

Code: O(n) by implementing a unique normalization

Thanks jianchaolifight's solution

Last updated

Was this helpful?