Tags: LeetCode DSA Arrays & Hashing
Prompt:
Given an array of strings strs, group all anagrams together into sublists. You may return the output in any order.
An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.
Example 1:
Input: strs = ["act","pots","tops","cat","stop","hat"]
Output: [["hat"],["act", "cat"],["stop", "pSolution:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs)
{
//init vector with 26 0 values for all alphabet letters
std::map<std::array<int, 26>, vector<string>> hashmap; //count vec -> matching anagram vec
for(const string& str : strs)
{
std::array<int, 26> countVec{};
for(char ch : str)
{
//index the array at the char and increment by one to count it
countVec[ch - 'a']++;
}
//add this string to the vector value in the hashmap based on the key
hashmap[countVec].push_back(str);
}
//loop over the dictionary and add all values to the return string
vector<vector<string>> returnVec;
for(auto& [count, stringVec] : hashmap)
{
returnVec.push_back(std::move(stringVec));
}
return returnVec;
}
};Explanation:
Okay so this one took me a little while, basically what I first tried to do was to loop over the strings and count up the ascii values of their characters, and then based on that determine if there were any other values that summed up to this, and so they were anagrams. This does work, but it also catches things that are not anagrams, so ad == bc or something of the sort where they both equal 197, so this did not work.
At this point I sought out a hint and was told to do something similar to that of the easy version of this called valid anagram where you basically set up a count table for each of the characters in two strings using a hashmap. So that is kind of what happens here.
Basically, the code loops over each string and then increments a corresponding array of 26 initial zero values. It uses the character to index into one of the 26 and then increment this. This is basically the idea of directly counting each one of the letters. Doing so, then allows you to use this array as a key into a hashmap of vector<string> where you just push over the string that has that matching count array.
So that is pretty much it, you set up the count array and then use it to index into a hashmap and then push back the given string to group the anagrams.
There is also a secondary solution where you can do things like sort the string, and then use this sorted string value as the actual key for the hashmap. So you basically sort the string which puts it into least to greatest based on value and the you use this to index into the hashmap, so all anagrams end up being the same key, technically a little bit slower than my solution, but it does look cleaner.