Anagram Checker
Checks if two strings are anagrams, ignoring case, spaces, and non-alphanumeric characters
Problem Overview
🔤 What are Anagrams?
Anagrams are words or phrases formed by rearranging letters of another word, using all original letters exactly once. Think "listen" → "silent" or "The Morse Code" → "Here come dots"!
- This Implementation Handles:
- Case-insensitive matching ("Listen" = "SILENT")
- Whitespace and punctuation removal ("Tea!" = "eat")
- Mixed alphanumeric characters ("a1b2" = "2b1a")
- Input validation and error handling
- Two Algorithmic Approaches:
- Sorting Method: Sort both strings and compare (simple but slower)
- Hash Map Method: Count character frequencies (optimal for large inputs)
- Word games and puzzles
- Cryptography and code-breaking
- Data deduplication algorithms
- String similarity detection
Concepts
string manipulationsortinghash mapsregular expressions
Complexity Analysis
Time:O(n log n) for sorting, O(n) for hash map
Space:O(n)
Solutions
areAnagrams
Time: O(n log n) | Space: O(n)
export function areAnagrams(str1: string, str2: string): boolean {
if (typeof str1 !== 'string' || typeof str2 !== 'string') throw new Error("Inputs must be strings");
const anagramPreparer = (str: string): string => str.toLowerCase().replace(/[^a-z0-9]/g, '').split('').sort().join('');
return anagramPreparer(str1) === anagramPreparer(str2);
}Examples & Test Cases
#1Classic pair
Input:
[
"listen",
"silent"
]Output:
true#2Non-anagram
Input:
[
"hello",
"world"
]Output:
false#3With punctuation
Input:
[
"Tea!",
"eat"
]Output:
true#4Empty strings
Input:
[
"",
""
]Output:
true#5With numbers
Input:
[
"rat1",
"tar1"
]Output:
true#6With spaces
Input:
[
"a b c",
"cba!"
]Output:
true