#49. Group Anagrams

ยท

1 min read

https://leetcode.com/problems/group-anagrams/description/?envType=daily-question&envId=2024-02-06


var groupAnagrams = function (strs) {

    const map = new Map

    for (let str of strs) { 

        const sortedStr = str.split('').sort().join('')

        if (!map.has(sortedStr)) map.set(sortedStr, [])

        map.get(sortedStr).push(str)

    }

    return Array.from(map.values())
};

To group all anagram An anagram is a literary device where the letters that make up a word, phrase, or name are rearranged to create new ones, we loop through the strings and sort the current word. Next we check if it is in a map that was instantiated earlier, if is isn't, we add it to the map as a key and give it an empty array as value, this empty array is then used to store all its anagram if they exist.

ย