DEV Community

OlumideSamuel
OlumideSamuel

Posted on

Group Anagram. (DSA Series 2)

Problem

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.

  • Example
  • Input: strs = ["eat","tea","tan","ate","nat","bat"]
  • Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
  • Input: strs = [""]
  • Output: [[""]]
  • Input: strs = ["a"]
  • Output: [["a"]] */

Solution


/**
 * for each item in array, sort alphabetically, then add sorted item to map as key, push index to value array eg; {aet:[0,1,3], ...}
 * return values of every word(key) in the map as an array.
 * Time Complexity is O(n)... I think. _Not sure if the sorting of each word takes an additional O(n)_ 
 */
function groupAnagram(arr){
    const map = {}
    for(let i = 0; i < arr.length; i++) {
       const sortedWord = [...arr[i] ].sort((a,b)=> a.localeCompare(b)).join();
       map[sortedWord] = map[sortedWord] !== undefined ? [...map[sortedWord], arr[i]] : [arr[i]]
    }

    return Object.values(map);
}
Enter fullscreen mode Exit fullscreen mode

Anyway, if you have a better way of solving this, you can drop your solution in the comments. I'm no expert. Just learning aloud.

Don't forget to like, share and drop a comment. :)

Top comments (0)