forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0242-valid-anagram.js
64 lines (52 loc) · 1.7 KB
/
0242-valid-anagram.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
/**
* Sort - HeapSort Space O(1) | QuickSort Space O(log(N))
* Time O(N * logN) | Space O(N)
* https://leetcode.com/problems/valid-anagram/
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = (s, t) => {
const isEqual = s.length === t.length;
if (!isEqual) return false;
return reorder(s) === reorder(t); /* Time O(N * logN) | Space O(N) */
};
const reorder = (str) => str
.split('') /* Time O(N) | Space O(N) */
.sort((a, b) => a.localeCompare(b))/* Time O(N * log(N)) | Space O(1 || log(N)) */
.join(''); /* Time O(N) | Space O(N) */
/**
* Hash Map - Frequency Counter
* Time O(N) | Space O(1)
* https://leetcode.com/problems/valid-anagram/
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = (s, t, map = new Map()) => {
const isEqual = s.length === t.length;
if (!isEqual) return false;
addFrequency(s, map); /* Time O(N) | Space O(1) */
subtractFrequency(t, map); /* Time O(N) | Space O(1) */
return checkFrequency(map);/* Time O(N) */
};
const addFrequency = (str, map) => {
for (const char of str) {/* Time O(N) */
const count = (map.get(char) || 0) + 1;
map.set(char, count); /* Space O(1) */
}
}
const subtractFrequency = (str, map) => {
for (const char of str) {/* Time O(N) */
if (!map.has(char)) continue;
const count = map.get(char) - 1;
map.set(char, count); /* Space O(1) */
}
};
const checkFrequency = (map) => {
for (const [ char, count ] of map) {/* Time O(N) */
const isEmpty = count === 0;
if (!isEmpty) return false;
}
return true;
}