Group Anagram. (DSA Series 2)

olumidesamuel_

OlumideSamuel

Posted on May 15, 2022

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. :)

💖 💪 🙅 🚩
olumidesamuel_
OlumideSamuel

Posted on May 15, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related