DEV Community

OlumideSamuel
OlumideSamuel

Posted on

4 3

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

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

Okay