C# Program to Check Anagram with Example and Explanation
ToCharArray() and Array.Sort(), then compare the sorted arrays with SequenceEqual().Examples
How to Think About It
Algorithm
Code
using System; using System.Linq; class Program { static bool AreAnagrams(string s1, string s2) { var arr1 = s1.ToLower().Replace(" ", "").ToCharArray(); var arr2 = s2.ToLower().Replace(" ", "").ToCharArray(); Array.Sort(arr1); Array.Sort(arr2); return arr1.SequenceEqual(arr2); } static void Main() { Console.WriteLine(AreAnagrams("listen", "silent")); Console.WriteLine(AreAnagrams("hello", "world")); Console.WriteLine(AreAnagrams("Dormitory", "Dirty room")); } }
Dry Run
Let's trace the example "Dormitory" and "Dirty room" through the code.
Normalize strings
"Dormitory" -> "dormitory", "Dirty room" -> "dirtyroom" (lowercase and no spaces)
Convert to char arrays
arr1 = ['d','o','r','m','i','t','o','r','y'], arr2 = ['d','i','r','t','y','r','o','o','m']
Sort arrays
arr1 sorted = ['d','i','m','o','o','r','r','t','y'], arr2 sorted = ['d','i','m','o','o','r','r','t','y']
Compare arrays
Both sorted arrays are equal, so return True
| Step | arr1 | arr2 |
|---|---|---|
| Initial | dormitory | dirtyroom |
| After sort | d i m o o r r t y | d i m o o r r t y |
Why This Works
Step 1: Normalize input
We convert both strings to lowercase and remove spaces to treat letters equally regardless of case or gaps.
Step 2: Sort characters
Sorting the characters puts letters in order, so if two strings have the same letters, their sorted forms will match.
Step 3: Compare sorted arrays
If the sorted character arrays are exactly the same, the strings are anagrams; otherwise, they are not.
Alternative Approaches
using System; using System.Collections.Generic; class Program { static bool AreAnagrams(string s1, string s2) { var dict = new Dictionary<char, int>(); foreach (var c in s1.ToLower().Replace(" ", "")) { dict[c] = dict.GetValueOrDefault(c, 0) + 1; } foreach (var c in s2.ToLower().Replace(" ", "")) { if (!dict.ContainsKey(c)) return false; dict[c]--; if (dict[c] < 0) return false; } return true; } static void Main() { Console.WriteLine(AreAnagrams("listen", "silent")); Console.WriteLine(AreAnagrams("hello", "world")); Console.WriteLine(AreAnagrams("Dormitory", "Dirty room")); } }
using System; using System.Linq; class Program { static bool AreAnagrams(string s1, string s2) { var a = s1.ToLower().Replace(" ", "").GroupBy(c => c).OrderBy(g => g.Key); var b = s2.ToLower().Replace(" ", "").GroupBy(c => c).OrderBy(g => g.Key); return a.SequenceEqual(b, new CharGroupComparer()); } class CharGroupComparer : IEqualityComparer<IGrouping<char, char>> { public bool Equals(IGrouping<char, char> x, IGrouping<char, char> y) { return x.Key == y.Key && x.Count() == y.Count(); } public int GetHashCode(IGrouping<char, char> obj) => obj.Key.GetHashCode(); } static void Main() { Console.WriteLine(AreAnagrams("listen", "silent")); Console.WriteLine(AreAnagrams("hello", "world")); Console.WriteLine(AreAnagrams("Dormitory", "Dirty room")); } }
Complexity: O(n log n) time, O(n) space
Time Complexity
Sorting each string takes O(n log n) time where n is the string length, which dominates the runtime.
Space Complexity
Extra space is used for character arrays and sorting, so space complexity is O(n).
Which Approach is Fastest?
Counting characters with a dictionary can be faster (O(n)) than sorting but uses more memory; sorting is simpler and good for short strings.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sorting and comparing | O(n log n) | O(n) | Simple and short strings |
| Character frequency count | O(n) | O(n) | Long strings, performance critical |
| LINQ GroupBy method | O(n log n) | O(n) | Readable code, moderate performance |