Algorithm 202 (My Interview Question): Grouping Anagrams in 3 Ways
Tags: algorithms, javascript, beginners, anagrams
Published: 2020-03-23 19:55:24

Last year, I had a ``technical interview`` and one of the questions was on ``Anagrams``. I solved the problem in 3 ways today and I want to share it with you in a moment. 

<pre>
Question:

Given an array of strings, group anagrams together.

Anagram: These are words that are made up of the same letters but in different orders.

Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"]

Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

</pre>

If you have been following my Algorithm series, then you are well fortified for this challenge. 

```javascript
  
groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]);

/*
  [ [ 'ate', 'eat', 'tea' ], [ 'nat', 'tan' ], [ 'bat' ] ]
*/
```

### Prerequisite
1. [String Reversal](https://dev.to/ebereplenty/algorithm-101-7-ways-to-reverse-a-string-15cb)
2. [Word Anagram](https://dev.to/ebereplenty/algorithm-101-3-ways-to-check-if-two-words-are-anagrams-1j6l)
3. [Sentence Anagram](https://dev.to/ebereplenty/algorithm-101-3-ways-to-check-if-two-sentences-are-anagrams-55jc)
4. [Array Chunking](https://dev.to/ebereplenty/algorithm-202-array-chunking-in-3-ways-1ank)
5. [Array Merging Without Duplicates](https://dev.to/ebereplenty/algorithm-202-array-merging-without-duplicates-in-4-ways-17h3)


### Solution 

* .map(), sort(), join(), Set(), forEach(), filter(), push, spread operator

```javascript
      function groupAnagrams(array) {
        let finalArray = [];

        // rearrange each word to check for anagram
        let rearranged = array.map(element => {
          return [...element].sort().join("");
        });

        // remove duplicates
        let uniqueArray = [...new Set(rearranged)];

        // compare original array with dupliates
        uniqueArray.forEach(word => {
          let chunk = array.filter(char => word === [...char].sort().join(""));

          finalArray.push(chunk.sort());
        });

        return finalArray;
      }
```

* for...of...loop, sort(), join(), filter(), push, split(), indexOf()

```javascript
      function groupAnagrams(array) {
        let finalArray = [];
        let rearranged = [];

        // rearrange each word to check for anagram
        for (element of array) {
          rearranged.push(
            element
              .split("")
              .sort()
              .join("")
          );
        }

        // remove duplicates
        let uniqueArray = rearranged.filter(
          (member, index) => rearranged.indexOf(member) === index
        );

        // compare original array with dupliates
        for (word of uniqueArray) {
          let chunk = [];

          for (char of array) {
            if (
              word ===
              char
                .split("")
                .sort()
                .join("")
            ) {
              chunk.push(char);
            }
          }
          finalArray.push(chunk.sort());
        }
        return finalArray;
      }
```

* for...loop, while...loop, sort(), join(), push(), split(), includes()

```javascript
      function groupAnagrams(array) {
        let finalArray = [];
        let rearranged = [];

        // rearrange each word to check for anagram
        let i = 0;
        while (i < array.length) {
          rearranged.push(
            array[i]
              .split("")
              .sort()
              .join("")
          );
          i++;
        }

        // remove duplicates
        let uniqueArray = [];
        for (let j = 0; j <= rearranged.length; j++) {
          if (!uniqueArray.includes(rearranged[j])) {
            uniqueArray.push(rearranged[j]);
          }
        }

        // compare original array with dupliates
        let counter = 0;
        while (counter < uniqueArray.length) {
          let chunk = [];

          for (let k = 0; k < array.length; k++) {
            if (
              uniqueArray[counter] ===
              array[k]
                .split("")
                .sort()
                .join("")
            ) {
              chunk.push(array[k]);
            }
          }

          if (chunk.length != 0) {
            finalArray.push(chunk.sort());
          }
          counter++;
        }
        return finalArray;
      }
```

### Conclusion
Interview questions like this one we just solved tends to test how far you have dived into algorithm. As you must have noted, the solution to just this problem is built upon other 5 algorithms we have solved in the past. So starting from the basics is very important.

There are many ways to solve problems programmatically. I will love to know other ways you solved yours in the comment section.

> Up Next: [Algorithm 101: 4 Ways to FizzBuzz a Single Number](https://dev.to/ebereplenty/algorithm-101-4-ways-to-fizzbuzz-a-single-number-380d)

If you have questions, comments or suggestions, please drop them in the comment section.

You can also follow and message me on social media platforms. 

**[Twitter](https://twitter.com/eberetwit) | [LinkedIn](https://www.linkedin.com/in/samson-ebere-njoku-profile/) | [Github](https://github.com/EBEREGIT)**

Thank You For Your Time.