The problem is, a bunch of strings will be give in an array, we need to we need to group the anagrams together.
This is a both grouping and anagram problem
First approach
My first approach was the classic hashmap approach, we store them together with their count and print them.
What i thought at first was that we can check the len of the words present and if they are same then we can say that the given word is an anagram
The major different between this and the regular anagram problem is that in regular anagram we just return the bool if the given word is an anagram.
But in here, we cant do that as the list may contain the same len of letters but they can be any different alphabets.
Therefore with the help of my close friend (ChatGPT), I was able to figure out that we cant really compare the len, instead we sort them individually and store them in the hashmap.
Solution
The solution goes pretty much like this,.
we create an hashmap, we loop through the array.
We then sort every str from strs and join them to form the sorted word
Now we use the sorted word as the key for the hash and the original str become the values of the hash
we can use dictionarydict in python that automatically creates key and empty value when the key is absent
Or we can create the key manually by using the if statements.
in the end we return them as list of hash values
Code
classSolution:defgroupAnagrams(self, strs: List[str])-> List[List[str]]: hsh ={}for s in strs: key =''.join(sorted(s))if key notin hsh: hsh[key]=[] hsh[key].append(s)returnlist(hsh.values())
Conclusion
This was a fun problem to solve and as simple as it seems, it was a problem to think and solve.