Skip to content

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.

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

Solution

Use a hash table to store the anagrams. For each string, sort the characters and use the sorted string as a key in the hash table. Add the original string to the array of anagrams for that key. Finally, return the values of the hash table as an array.

Implementation

/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function (strs) {
const anagrams = new Map();
for (const s of strs) {
const sortedWord = s.split("").sort().join("");
const wordAnagrams = anagrams.get(sortedWord) ?? [];
wordAnagrams.push(s);
anagrams.set(sortedWord, wordAnagrams);
}
return Array.from(anagrams.values());
};