Group anagrams
Group words that are anagrams while preserving the order in which groups and words first appear.
Course progress
Problem 43 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
words = ["eat", "tea", "tan", "ate", "nat", "bat"]
Expected output
eat,tea,ate tan,nat bat
What is happening?
Words with the same sorted-letter signature share a group: aet groups eat, tea, and ate; ant groups tan and nat; bat stands alone.
Solution strategy
Build the right mental model
Sort each word's characters to create a canonical signature. A dictionary finds the matching group, while a separate list preserves group insertion order.
Core concepts
dictionary · sorting strings
Complexity
Time O(n x k log k), space O(n x k), where k is the maximum word length.
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for group-anagrams
using System;
using System.Collections.Generic;
class Program
{
static List<List<string>> GroupAnagrams(string[] words)
{
var bySignature = new Dictionary<string, List<string>>();
var groups = new List<List<string>>();
foreach (string word in words)
{
char[] characters = word.ToCharArray();
Array.Sort(characters);
string signature = new string(characters);
List<string> group;
if (!bySignature.TryGetValue(signature, out group))
{
group = new List<string>();
bySignature[signature] = group;
groups.Add(group);
}
group.Add(word);
}
return groups;
}
static void Main()
{
foreach (var group in GroupAnagrams(new[] { "eat", "tea", "tan", "ate", "nat", "bat" }))
Console.WriteLine(string.Join(",", group));
}
}Knowledge check
Questions students often ask
What is the main idea behind group anagrams?
Sort each word's characters to create a canonical signature. A dictionary finds the matching group, while a separate list preserves group insertion order.
What is the time and space complexity of this solution?
Time O(n x k log k), space O(n x k), where k is the maximum word length.
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.