-
Program to Group Anagrams
-
When working with string manipulation problems, “Group Anagrams” is one of the most commonly asked questions in technical interviews. The goal is simple: Words that are anagrams of each other must be placed inside the same group.
Problem Statement
Input: { "eat", "tea", "ate" }
Output: [ ["eat", "tea", "ate"] ]All these words contain the same characters, so they must be grouped together.
Logic to group anagrams:
- Pick each word.
- Sort its characters.
- "eat" → "aet"
- "tea" → "aet"
- "ate" → "aet"
- Use the sorted string as a key in a dictionary.
- Add all words with the same key into the same list.
- The dictionary values become the grouped output.
1. C# Program: Group Anagrams Using Dictionary
Output:using System; using System.Collections.Generic; using System.Linq; public class GroupAnagramsUsingDictionary { public static void Main() { string[] words = { "eat", "tea", "ate", "late", "tale" }; var result = GroupAnagrams(words); foreach (var group in result) { Console.WriteLine("[ " + string.Join(", ", group) + " ]"); } } static List<List<string>> GroupAnagrams(string[] words) { Dictionary<string, List<string>> map = new Dictionary<string, List<string>>(); foreach (var word in words) { // Create sorted version of the word (key) char[] chars = word.ToCharArray(); Array.Sort(chars); string key = new string(chars); // Add to dictionary if (!map.ContainsKey(key)) map[key] = new List<string>(); map[key].Add(word); } return map.Values.ToList(); } }[ eat, tea, ate ] [ late, tale ]
2. C# Program: Group Anagrams Using LINQ
Output:using System; using System.Linq; using System.Collections.Generic; public class LinqGroupAnagrams { public static void Main() { string[] words = { "eat", "tea", "ate", "late", "tale", "grown", "wrong" }; var result = words .GroupBy(word => new string(word.OrderBy(c => c).ToArray())) .Select(group => group.ToList()) .ToList(); foreach (var group in result) { Console.WriteLine("[ " + string.Join(", ", group) + " ]"); } } }[ eat, tea, ate ] [ late, tale ] [ grown, wrong ]