Logo

dev-resources.site

for different kinds of informations.

Group Anagrams

Published at
4/17/2022
Categories
leetcode
blind75
strings
Author
Stylus07
Categories
3 categories in total
leetcode
open
blind75
open
strings
open
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"]]
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);
}

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

Featured ones: