Group Anagrams Together

Given an array of strings or a list of words, write a code to group anagrams together.

what are Anagrams?

Two strings are said to be anagrams of each other if it contains the same characters, only the order of character in both the strings is different.

Check whether two strings are anagrams of each other or not

For example, Word “car” and “rac” are anagrams of each other. As both, the strings contain the same number of characters only the order of character is different in both the strings.

Now, let’s understand this problem statement with example.

For example:

Input: {“eat”, “tea”, “tan”, “ate”, “nat”, “bat”}

Output:

Print Anagrams Together

In this example, you can see all anagrams are grouped together. We understood the problem statement, let’s think about how we can solve this problem efficiently.

Programming video tutorials

Group Anagrams Together – Java Code

If two strings are anagrams of each other, then their sorted sequence is the same. By keeping this point in mind we can solve this problem.

Here are the following steps to group anagrams.

i) Traverse a list of string.

ii) Pick each string and sort it. For sorting, first, convert a string into a character array and then sort this array.

iii) Create a map and put sorted string as a key to this map to group all the anagrams together.

Sort characters by Frequency

The time complexity of this approach is O(NMlogM), where N is the length of the array and M is the longest word in an array.

In this video tutorial, I have explained this approach to the group and print all Anagrams together.

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.