space: O(n) for answers, and 26 length arrays
var groupAnagrams = function (strs) {
const memo = {};
for (let i = 0; i < strs.length; i++) {
const word = strs[i];
const arr = new Array(26).fill(0);
for (const c of word) {
const code = c.charCodeAt();
arr[code - 'a'.charCodeAt()]++;
}
const hashed = arr.join();
if (memo[hashed] === undefined) {
memo[hashed] = [];
}
memo[hashed].push(word);
}
return Object.values(memo);
};
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function (strs) {
const memo = {};
for (let i = 0; i < strs.length; i++) {
const word = strs[i];
const sorted = [...word].sort((a, b) => {
return a.localeCompare(b)
}
).join('');
if (memo[sorted] === undefined) {
memo[sorted] = [];
}
memo[sorted].push(word);
}
return Object.values(memo);
};