-
Notifications
You must be signed in to change notification settings - Fork 0
/
group-anagrams.js
48 lines (28 loc) · 996 Bytes
/
group-anagrams.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
39
40
41
42
43
44
45
46
47
48
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
// define output array
const output = []
// define map
const map = {}
// loop through strs
for(let i = 0; i < strs.length; i++) {
// sort current str
const strSorted = strs[i].split('').sort().join('')
// if sorted string is present in map
if(map[strSorted]!==undefined) {
// get index of output array to push current str
output[map[strSorted]].push(strs[i])
} else {
// push current str into output array
output.push([strs[i]])
// add sorted str to map
// set map[sorted str] = output array length - 1
map[strSorted] = output.length-1
}
}
// return output array
return output
};