Skip to content

Instantly share code, notes, and snippets.

@sAVItar02
Created November 9, 2024 07:20
Show Gist options
  • Save sAVItar02/6613b4b570514b5837935cfb5e6c6649 to your computer and use it in GitHub Desktop.
Save sAVItar02/6613b4b570514b5837935cfb5e6c6649 to your computer and use it in GitHub Desktop.
Group Anagrams
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
let map = {};
let res = [];
for(let i=0; i<strs.length; i++) {
let temp = strs[i].split("");
temp.sort();
temp = temp.join('');
if(map[temp]) map[temp].push(strs[i]);
else {
map[temp] = [strs[i]];
}
}
Object.keys(map).forEach(key => {
res.push(map[key]);
})
return res;
};
// Sort the characters of the string and store it as a key in a map
// For every string where the sorted alphabets match a key in the map, store it in the array
// If no match, then create a new key and store it in an array
// Return the values in the map as an array
// Time: O(n * m * log(m))
// Space: O(n * m)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment