Difficulty: Medium
Very similar problem to the valid anagram question that was done two days ago.
Here, we want to group each string into valid anagrams of each other. Intuitively, we can think about keeping track of ‘anagram groups’ where every element in each group is a valid anagram of each other, which can be done with a hashmap.
The problem then would be what do we use as the key or identifier for each of these groups? A few options for the key are:
{ "aet": ["eat", "ate", "tea"] }hello -> ehllo){ {'a': 1, 'e': 1, 't': 1}: ["eat", "ate", "tea"] }I feel like either option 1 or 3 is very nice… The overhead in option 1 would be sorting each character and then string comparison while the overhead in option 3 would be the memory of the array and array comparison…
I think option 1 is slightly nicer and easier to write so I’ll go with that… so again, we need to learn a bit more cpp :D
std::sort(word.begin(), word.end()) sorts the word in place (in the <algorithm> header)for loop, we get back pair<keyType, valueType> objectclass Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> anagramGroups {};
for (string word: strs) {
string sortedWord = word;
sort(sortedWord.begin(), sortedWord.end());
if (anagramGroups.contains(sortedWord)) {
anagramGroups[sortedWord].push_back(word);
} else {
anagramGroups[sortedWord] = {word};
}
}
vector<vector<string>> result {};
for (const pair<string, vector<string>>& element: anagramGroups) {
result.push_back(element.second);
}
return result;
}
};
Time Complexity:
O(m * n log n)-mis the number of words in the list,nis the max length of the stringSpace Complexity:
O(mn)Time Taken:
7m 36s