DEV Community

Stylus07
Stylus07

Posted on

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"]]
Enter fullscreen mode Exit fullscreen mode

var groupAnagrams = function (strs) {
    if (!strs || !strs.length) {
        return null;
    }
    let anagrams = {};
    for (let x = 0; x < strs.length; x++) {
        const sortedWord = strs[x].split('').sort().join();
        if (sortedWord in anagrams) {
            anagrams[sortedWord].push(strs[x])
        } else {
            anagrams[sortedWord] = [strs[x]];
        }
    }
    return Object.values(anagrams);
}
Enter fullscreen mode Exit fullscreen mode

Time Complexity : O(w*n*log(n))
Space Complexity : O(wn)

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Using the upcoming Array.groupBy (already available in Firefox Nightly):

const groupAnagrams = arr=>Object.values(arr.groupBy(i=>[...i].sort()))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
styluso7 profile image
Stylus07

@jonrandy thanks