DEV Community

Stylus07
Stylus07

Posted on

2 2

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)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay