Group Anagrams
As I am practicing my coding and working out my logic and problem-solving muscle. I ran into this particular fun problem in leetcode called group anagrams, I thought of sharing my approach to solve it.
It says that given an array of strings strs, group the anagrams together. You can return the answer in any order.
Example1
Input: strs = [“eat”,”tea”,”tan”,”ate”,”nat”,”bat”].
Output: [[“bat”],[“nat”,”tan”],[“ate”,”eat”,”tea”]]
Understanding what is the problem asking for.
It wants me to return an array of groups of anagrams from an array of words. In order to achieve that I have to know what is an anagram. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase.
The best way to know if two words or phrases have the same letters is to sort all of their letters and see if they match. An example is “dormitory” and “dirty room” if you organize the letters of both it would be “dimoorrty”.
Implementing a solution
Now that we know, what an anagram is and how to identify anagrams phrase, we can proceed to the solution. The algorithm is going to iterate over the array of words and is going to start grouping the words that are anagrams in a javascript object where the key is the sorted letters of the word or phrase if the key exists we save the current word or phrase under that key if it doesn't exist we insert that key and initialize its value to an empty array before pushing the current word. Once we go over all the words and grouped them with their anagrams we return an array containing all the values of the javascript object.