Group Anagrams

Bryam Vicente
4 min readJun 7, 2021

--

For this blog, I’ll be going over another popular problem on LeetCode. Note that I’ll be using JavaScript to solve this problem! Here’s the prompt:

In other words, the prompt is asking us to create a function that takes in an array of strings and returns an array with subarrays. These subarrays will contain the different types of phrases that can be created with the same letters. The examples are very helpful in demonstrating what the inputs and outputs should be!

Before doing any code, the first step should always be planning ahead or pseudo code. So let’s start with that! Here’s a picture of my pseudo code:

Now that we know what to do, let’s go through each step together!

The first two steps mention that we need to create a variable that’s going to represent the hash table and create a for loop to iterate over the array strs. Here’s what the code should look like right now:

Inside of the for loop, there are a few steps that need to take place. For example, we need to sort the strings in alphabetical order to make it easier for the hash to keep track of each letter. This is what the sorted strings are supposed to look like when using the the console.log() on line 19:

The first string on the array is “eat” and we can see how that turns into aet when sorted. For the third string which is “tan”, we can see how it turns into ant when sorted.

The next step is to create a conditional that turns the current element being iterated inside strs (strs[i]) into a key inside of hashTable if it doesn’t exist. If the current element does exist then push that string inside of the subarray that corresponds with it’s key (aet, ant). Here’s what the code should look like so far:

To explain what’s happening with hashTable, I decided to place two console.logs on lines 12 and 21. One will represent hashTable[sortedString] before the if statement and the other will represent what hashTable[sortedString]looks like after. Here are the results of that:

If you’re still confused on what’s going, here’s the before and after for the actual hash table (hashTable):

For the final step, all we have to do now is return hashTable. On the examples from Leetcode, it shows that the output should still be an array. One way we can do this is by using a built in method that converts an object to an array (Object.values()) ! Here’s the full solution for this problem:

Here are the results for lines 23–25:

Here’s the solution on LeetCode:

I hope this blog was helpful in any way! I’m going to continue working on this problem and see if there are more efficient ways of solving this problem. For more info on for loops, hash tables, and built in methods such as Object.values, .split(), .sort(), .join() and .push() checkout the resource section below!

Resources:

--

--

No responses yet