7. Group Anagrams

Trick: All anagram are same when they are sorted.

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Solution :

class Solution
{
public:
    vector<vector<string>> groupAnagrams(vector<string> &strs)
    {

        unordered_map<string, vector<string>> m;
        vector<vector<string>> v;

        for (int i = 0; i < strs.size(); i++)
        {
            string s = strs[i];
            sort(s.begin(), s.end());

            if (m.find(s) == m.end())
            {
                vector<string> k;
                k.push_back(strs[i]);
                m.insert({s, k});
            }
            else
            {
                vector<string> k;
                k = m[s];
                k.push_back(strs[i]);
                m[s] = k;
            }
        }

        for (auto itr = m.begin(); itr != m.end(); itr++)
        {
            vector<string> vect;
            vect = itr->second;
            v.push_back(vect);
        }

        return v;
    }
};

Last updated