49. Group Anagrams

Group Anagrams

Group Anagrams

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

 

Example 1:

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


Example 2:

Input: strs = [""]
Output: [[""]]


Example 3:

Input: strs = ["a"]
Output: [["a"]]

 

Constraints:

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters.
Idea:

First, we make a hash map (you can use an object if you want, which is also a hash map, but Map() is more efficient with read/write) to store different combinations of letters we come across.

We'll store these combinations as string arrays that are sorted then stringified: For example, for the strs input ['eat', 'tea', 'bat'], our map will contain the keys "['a', 'e', 't']" and "['a', 'b', 't']". The values will be arrays including the original words: respectively, ['eat', 'tea'] and ['bat'].

Note: We stringify arrays because this allows us to compare them; [5] === [5] will equal false, but "[5]" === "[5]" equals true.

So for each word in strs, split it into an array then sort and stringify it; if it matches a key in our map, we concatenate the key's value – an array – with the word. For example, the sorted, stringified array of 'tab' matches "['a', 'b', 't']", so we update the value of that key to ['bat', 'tab']. Otherwise, we make a new key and give it a value of an array containing the word.


Let`s code it!

var groupAnagrams = function(strs) {
    let anagrams = new Map()
    
    for (let i = 0; i < strs.length; i++) {
        const letters = strs[i].split('').sort().toString()
        if (anagrams.has(letters)) {
            anagrams.set(
                letters, 
                anagrams.get(letters).concat([strs[i]])
            )
        } else {
            anagrams.set(letters, [strs[i]])
        }
    }
    return [...anagrams.values()]
};


Conclusion

That’s all folks! In this post, we solved LeetCode problem #49. Group Anagrams

I hope you have enjoyed this post. Feel free to share your thoughts on this.

You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.


In this blog, I have tried to collect & present the most important points to consider when improving Data structure and logic, feel free to add, edit, comment, or ask. For more information please reach me here
Happy coding!

Comments

Popular Post