-
Notifications
You must be signed in to change notification settings - Fork 0
/
Group_Anagrams.js
41 lines (30 loc) · 1.05 KB
/
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
// ------------------------Description-----------------------------------------
// Your job is to group the words in anagrams.
// What is an anagram ?
// star and tsar are anagram of each other because you can rearrange the letters for star to obtain tsar.
// Example
// A typical test could be :
// // input
// ["tsar", "rat", "tar", "star", "tars", "cheese"]
// // output
// [
// ["tsar", "star", "tars"],
// ["rat", "tar"],
// ["cheese"]
// ]
// ----------------------------------------------------------------------------
const groupAnagrams = (words) => {
const anagramsMap = new Map();
words.forEach((word) => {
const sortedWord = word.split("").sort().join("");
if (anagramsMap.has(sortedWord)) {
anagramsMap.get(sortedWord).push(word);
} else {
anagramsMap.set(sortedWord, [word]);
}
});
return Array.from(anagramsMap.values());
};
// Test
const words = ["tsar", "rat", "tar", "star", "tars", "cheese"];
console.log(groupAnagrams(words)); //result => [ [ 'tsar', 'star', 'tars' ], [ 'rat', 'tar' ], [ 'cheese' ] ]