-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path49__medium__group-anagrams.js
112 lines (99 loc) · 1.6 KB
/
49__medium__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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*
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.
*/
/**
* @param {string[]} strs
* @return {string[][]}
*/
/**
*
* Time Complexity: O(NKlogK),
* where N is the length of strs,
* and K is the maximum length of a string in strs.
*
* Space Complexity: O(NK), the total information content stored in ans.
*
* 15m
*/
var groupAnagrams = function(strs) {
let map = {};
let res = [];
for (let i = 0; i < strs.length; i++) {
let key = hashKeyFromStr(strs[i]);
map[key] = map[key] || [];
map[key].push(strs[i]);
}
for (let arr of Object.values(map)) {
res.push(arr);
}
return res;
function hashKeyFromStr(str) {
return str
.split("")
.sort()
.join("");
}
};
/**
*
* O(NK) time
* O(NK) space
*
* 30m (you need to get the primes list...)
*/
var groupAnagrams = function(strs) {
const map = new Map();
const primes = [
2,
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97,
101,
107
];
strs.forEach(str => {
let key = 1;
for (let i = 0; i < str.length; i++) {
key = primes[str.charCodeAt(i) - "a".charCodeAt()] * key;
}
if (map.has(key)) {
let group = map.get(key);
group.push(str);
} else {
map.set(key, [str]);
}
});
return [...map.values()];
};