-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupAnagrams.js
More file actions
30 lines (25 loc) · 814 Bytes
/
GroupAnagrams.js
File metadata and controls
30 lines (25 loc) · 814 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//Given an array of strings strs, group the anagrams together. You can return the answer in any order.
//Example:
//Input: strs = ["eat","tea","tan","ate","nat","bat"]
//Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
//Time complexity: O(n⋅klogk)
//Runtime Complexity
//O(n*klogk), where n is the number of strings and k is the length of longest string
//Space Complexity
//O(n*k), where we sort and then create map key
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
let temp = new Map();
strs.forEach(s => {
let sorted = s.split("").sort().join("");
if(!temp.has(sorted)) {
temp.set(sorted, []);
}
temp.get(sorted).push(s);
});
//Array.from(temp.values())
return ([...temp.values()]);
};