Using Sorting
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function (strs) {
let res = new Map()
for (let s of strs) {
const key = s.split('').sort().join('')
if (!res.has(key)) {
res.set(key, []);
}
res.get(key).push(s);
}
return Array.from(res.values());
};
Using Sorting takes O(nlogn * m) time complexity
We can optimize to O(n * m) with Hashmap
Using HashMap
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function (strs) {
let res = new Map()
for (let s of strs) {
const count = new Array(26).fill(0);
for (c of s) {
count[c.charCodeAt(0) - "a".charCodeAt(0)] += 1;
}
const key = count.join(',')
if (!res.has(key)) {
res.set(key, []);
}
res.get(key).push(s);
}
return Array.from(res.values());
};
charCodeAt(index)
- Returns the ASCII/Unicode value of the character at the given
index
in a string. -
Example:
"a".charCodeAt(0) ā 97
(Unicode of 'a').
1ļøā£ res.get(key).push(s);
- Retrieves the array stored at
key
in theMap
. - Pushes
s
into the array in place (modifies existing array). - No need for
res.set(key, updatedArray)
because arrays are reference types.
2ļøā£ Array.from(res.values())
-
res.values()
returns an iterator of all values in theMap
. -
Array.from()
converts the iterator into a normal array. - Ensures the function returns a proper
string[][]
instead of an iterator.
Top comments (0)