C# || Group Anagrams – How To Group Array Of Anagrams Using C#

Print Friendly, PDF & Email

The following is a module with functions which demonstrates how to group an array of anagrams using C#.

1. Group Anagrams – Problem Statement

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

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

Example 2:

Input: strs = [""]
Output: [[""]]

Example 3:

Input: strs = ["a"]
Output: [["a"]]

2. Group Anagrams – Solution

The following is a solution which demonstrates how to group an array of anagrams.

The idea of this solution is to generate a simple hash key for each anagram.

The hash key is made up consisting of a digit, and a letter. These two values represents the character count, and the letter found in the given string.

For example, given the input ["eat","tea","tan","ate","nat","bat"] we create a hash for each anagram as follows:

anagram: eat, hash: 1a1e1t
anagram: tea, hash: 1a1e1t
anagram: tan, hash: 1a1n1t
anagram: ate, hash: 1a1e1t
anagram: nat, hash: 1a1n1t
anagram: bat, hash: 1a1b1t

The hash key is generated similar to the counting sort technique. We use this hash to group the anagrams together.

The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:


Was this article helpful?
👍 YesNo

Leave a Reply