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:
  1. Pick each word.
  2. Sort its characters.
    • "eat" → "aet"
    • "tea" → "aet"
    • "ate" → "aet"
  3. Use the sorted string as a key in a dictionary.
  4. Add all words with the same key into the same list.
  5. The dictionary values become the grouped output.

1. C# Program: Group Anagrams Using Dictionary


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();
    }
}
Output:


[ eat, tea, ate ]
[ late, tale ]


2. C# Program: Group Anagrams Using LINQ


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) + " ]");
        }
    }
}
Output:


[ eat, tea, ate ]
[ late, tale ]
[ grown, wrong ]