-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
38 lines (29 loc) · 784 Bytes
/
index.js
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
31
32
33
34
35
36
37
38
// Given an array of strings, group anagrams together.
// Example:
// Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
// Output:
// [
// ["ate", "eat", "tea"],
// ["nat", "tan"],
// ["bat"]
// ]
// Note:
// All inputs will be in lowercase.
// The order of your output does not matter.
// Solution
const groupAnagrams = function (strs) {
const mapping = {}, output = [];
for (let i = 0; i < strs.length; i++) {
const str = strs[i];
const sorted = str.split('').sort().join('');
if (mapping[sorted] === undefined) {
mapping[sorted] = [str];
} else {
mapping[sorted].push(str);
}
}
for (let arr in mapping) {
output.push(mapping[arr]);
}
return output;
};