-
-
Notifications
You must be signed in to change notification settings - Fork 155
/
Copy pathgroupAnagrams.js
64 lines (56 loc) · 2.19 KB
/
groupAnagrams.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
function groupAnagramsWithMap(arr) {
let anagramGroups = new Map();
for(let str of arr) {
let sortedString = str.split("").sort().join("");
if(anagramGroups.has(sortedString)) {
anagramGroups.get(sortedString).push(str);
} else {
anagramGroups.set(sortedString, [str]);
}
}
return Array.from(anagramGroups.values());
}
function groupAnagramsWithObject(arr) {
let anagramGroups = {};
for(let str of arr) {
let sortedString = str.split("").sort().join("");
let group = anagramGroups[sortedString];
if(group && group.length > 0) {
anagramGroups[sortedString].push(str);
} else {
anagramGroups[sortedString] = [str];
}
}
return Object.values(anagramGroups);
}
//Without sorting: TC(K * N) SC(K * N)
function groupAnagramsWithoutSorting(arr) {
let anagramGroups = {};
for(let str of arr) {
let charCount = Array(26).fill(0);
for(const ch of str.toLowerCase()){
charCount[ch.charCodeAt(0)- 'a'.charCodeAt(0)]
}
let charCountkey = charCount.join("");
if(!anagramGroups[charCountkey]) {
anagramGroups[charCountkey] = [];
}
anagramGroups[charCountkey].push(str);
}
return Object.values(anagramGroups);
}
// Multiple Anagrams
console.log("Input: ['eat', 'tea', 'tan', 'ate', 'nat', 'bat']");
console.log("Output1: ", groupAnagramsWithMap(['eat', 'tea', 'tan', 'ate', 'nat', 'bat']));
console.log("Output2: ", groupAnagramsWithoutSorting(['eat', 'tea', 'tan', 'ate', 'nat', 'bat']));
console.log("---------------");
// Mixed Case Anagrams
console.log("Input: ['Eat', 'Tea', 'Tan', 'Ate', 'Nat', 'Bat']");
console.log("Output1: ", groupAnagramsWithObject(['Eat', 'Tea', 'Tan', 'Ate', 'Nat', 'Bat']));
console.log("Output2: ", groupAnagramsWithoutSorting(['Eat', 'Tea', 'Tan', 'Ate', 'Nat', 'Bat']));
console.log("---------------");
// No Anagrams
console.log("Input: ['apple', 'orange', 'banana']");
console.log("Output1: ", groupAnagramsWithMap(['apple', 'orange', 'banana']));
console.log("Output2: ", groupAnagramsWithoutSorting(['apple', 'orange', 'banana']));
console.log("---------------");