...

/

Solution: Group Anagrams

Solution: Group Anagrams

Explore the solution to the problem of finding group anagrams in detail.

Solution: Using a dictionary and list

using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
/// <summary>
/// Method to find anagram pairs.
/// </summary>
/// <param name="arr">An array of strings.</param>
/// <returns>Group of anagrams.</returns>
public static List<List<string>> Anagrams(string[] lst)
{
// Empty dictionary which holds subsets of all anagrams together
Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>();
// traversing all the lst strings
foreach (string str in lst)
{
char[] charArray = str.ToCharArray();
// sorting the lst string and storing it in a key
Array.Sort(charArray);
string key = new string(charArray);
// if the key is already in the dictionary then appending the original lst(Anagram).
if (dictionary.ContainsKey(key))
{
dictionary[key].Add(str);
}
else // If there is no key in the dictionary
{
dictionary[key] = new List<string> { str };
}
}
// traversing the whole dictionary and concatenating values and keys
List<List<string>> result = new List<List<string>>();
foreach (var pair in dictionary)
{
if (pair.Value.Count >= 2)
{
result.Add(pair.Value.OrderBy(x => x).ToList());
}
}
result.Sort(CompareLists); // sort the arrays
return result;
}
public static int CompareLists(List<string> list1, List<string> list2)
{
int minLength = Math.Min(list1.Count, list2.Count);
for (int i = 0; i < minLength; i++)
{
int comparison = list1[i].CompareTo(list2[i]);
if (comparison != 0)
{
return comparison;
}
}
return list1.Count - list2.Count;
}
// Driver to test above code
static void Main(string[] args)
{
string[] lst = new string[]
{
"tom marvolo riddle ",
"abc",
"def",
"cab",
"fed",
"clint eastwood ",
"i am lord voldemort",
"elvis",
"old west action",
"lives"
};
List<List<string>> result = Anagrams(lst);
var resultsToPrint = new List<string>();
foreach (var anagram in result)
{
resultsToPrint.Add("[\"" + string.Join("\", \"", anagram) + "\"]");
}
Console.WriteLine("[" + string.Join(", ", resultsToPrint) + "]");
}
}

Explanation

This solution sorts each input string in ascending order and considers it a key and the ...