Anagram checker
Check whether two phrases contain the same letters in a different order, ignoring spaces, punctuation, and case.
Course progress
Problem 7 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
first = "Dormitory"; second = "Dirty room"
Expected output
True
What is happening?
After removing the space and ignoring case, both phrases contain exactly the same letters with the same frequencies, so they are anagrams.
Solution strategy
Build the right mental model
Build a frequency table by adding counts from the first phrase and subtracting counts from the second. Every final count must be zero.
Core concepts
dictionary · strings
Complexity
Time O(n + m), space O(k), where k is the number of distinct characters.
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for anagram-checker
using System;
using System.Collections.Generic;
class Program
{
static bool AreAnagrams(string first, string second)
{
var counts = new Dictionary<char, int>();
foreach (char raw in first)
{
if (!char.IsLetterOrDigit(raw)) continue;
char key = char.ToLowerInvariant(raw);
int count;
counts.TryGetValue(key, out count);
counts[key] = count + 1;
}
foreach (char raw in second)
{
if (!char.IsLetterOrDigit(raw)) continue;
char key = char.ToLowerInvariant(raw);
int count;
counts.TryGetValue(key, out count);
counts[key] = count - 1;
}
foreach (int count in counts.Values)
if (count != 0) return false;
return true;
}
static void Main()
{
Console.WriteLine(AreAnagrams("Dormitory", "Dirty room"));
}
}Knowledge check
Questions students often ask
What is the main idea behind anagram checker?
Build a frequency table by adding counts from the first phrase and subtracting counts from the second. Every final count must be zero.
What is the time and space complexity of this solution?
Time O(n + m), space O(k), where k is the number of distinct characters.
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.