49. Group Anagrams

0

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 1:Input: strs = [“eat”,”tea”,”tan”,”ate”,”nat”,”bat”]

Output: [[“bat”],[“nat”,”tan”],[“ate”,”eat”,”tea”]]

Example 2:Input: strs = [“”] Output: [[“”]]

Example 3:Input: strs = [“a”] Output: [[“a”]]

Constraints:

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters.

Solution

First attempt : (Can be optimized further)

var groupAnagrams = function(strs) {
    let output = [];
    let done = new Set();
    if(strs.length == 0){
        return [[""]];
    }
    else if(strs.length == 1){
        return [strs];
    }
    else{
    for(let i = 0; i<strs.length; i++){
        let group = [strs[i]];
        
        //console.log(done);
        if(!done.has(strs[i])){
            
        for(let j = i+1; j<strs.length;j++){
            if(isAnagram(strs[i],strs[j])){
                group.push(strs[j])
                done.add(strs[j])
               // strs.splice(j, 1); 
                
            }
        }
        done.add(strs[i]);
                //strs.splice(i, 1); 
        output.push(group);
        }
        
        
    }
}
    return output;
};
function isAnagram(stra,strb){
    let straa = stra.split("");
    let strbb = strb.split("");
    if(straa.length == strbb.length){
        let obj = {};
        for(let i = 0; i < straa.length;i++){
            if(obj[straa[i]]){
                obj[straa[i]]++;
            }
            else{
               obj[straa[i]] = 1; 
            }
        }
       
        for(let i = 0; i < strbb.length;i++){
            if(obj[strbb[i]]){
                obj[strbb[i]]--;
            }
            else{
                return false;
            }
        }
      
    }
    else{
        return false;
    }
    return true;
}

Optimized solution:

var groupAnagrams = function(strs) {
    let map = new Map();
    for(let str of strs) {
        let sorted = [...str].sort().join('');
        if(map.has(sorted)) {
            map.get(sorted).push(str);
        } else {
            map.set(sorted, [str]);
        }
    }
    return Array.from(map.values());
};

Leave a Comment

Skip to content