Grouping Anagrams from a Sequence of Words
Sat Mar 23 2024
Anagrams:
This method harnesses the power of sorting and mapping to elegantly categorize anagrams. By iterating over each word in the provided list, it creates a sorted key that represents the word's characters in a uniform order. This key serves as a unique identifier for anagrams, allowing the method to accumulate words with identical keys into groups. Utilizing a Map to maintain these groups ensures that each collection of anagrams is easily retrievable and distinct. The method culminates by outputting these groups, showcasing the anagrams together in a clear and organized manner.
1class Solution {
2  Anagrams(string_list) {
3    let m = new Map();
4    for (let i = 0; i < string_list.length; i++) {
5      const key = string_list[i].split('').sort().join('');
6
7      if (!m.has(key)) {
8        m.set(key, [string_list[i]]);
9      } else {
10        const group = m.get(key);
11        group.push(string_list[i]);
12        m.set(key, group);
13      }
14    }
15
16    for (const group of m.values()) {
17      console.log(group.join(' '));
18    }
19  }
20}
21
22let s = new Solution();
23s.Anagrams(['act', 'god', 'cat', 'dog', 'tac']);
24