Anagram Detector
Level: Beginner 15–30 minConcepts: AlgorithmsStringsValidation
Build an anagram detection system that can check pairs, filter lists, and group words by their anagram sets.
Requirements
Step 1: Pair Detection
Given two words, determine if they are anagrams of each other.
- An anagram uses exactly the same letters, the same number of times
- Comparison should be case-insensitive
- Spaces and punctuation are ignored
- A word is not an anagram of itself
Examples:
"listen"and"silent"→ true"hello"and"world"→ false"Astronomer"and"Moon starer"→ true"rail safety"and"fairy tales"→ true"cat"and"cat"→ false (same word)
Step 2: Find Anagrams in a List
Given a subject word and a list of candidates, return the candidates that are anagrams of the subject.
subject: "listen"
candidates: ["enlists", "google", "inlets", "banana", "silent"]
result: ["inlets", "silent"]
Step 3: Group Anagrams
Given a list of words, group them by their anagram sets.
input: ["eat", "tea", "tan", "ate", "nat", "bat"]
output: [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]
Test Cases
Pair detection:
| Word A | Word B | Anagram? |
|---|---|---|
"listen" | "silent" | true |
"hello" | "world" | false |
"cat" | "tac" | true |
"cat" | "cat" | false |
"Cat" | "tac" | true |
"" | "" | false |
"a" | "a" | false |
"ab" | "ba" | true |
"aab" | "abb" | false |
Find anagrams:
| Subject | Candidates | Result |
|---|---|---|
"listen" | ["silent", "tinsel"] | ["silent", "tinsel"] |
"listen" | ["hello", "world"] | [] |
"master" | ["stream", "maters", "pigeon"] | ["stream", "maters"] |
Group anagrams:
| Input | Groups |
|---|---|
["eat", "tea", "ate"] | [["eat", "tea", "ate"]] |
["abc", "def"] | [["abc"], ["def"]] |
[] | [] |
Bonus
- Find the longest anagram pair in a dictionary file
- Detect partial anagrams — words where one is an anagram of a substring of the other
- Generate all possible anagrams of a given word (permutations that are real words, given a dictionary)
Hint
The key insight: two words are anagrams if they have the same sorted characters. Sorting the letters of "listen" and "silent" both give "eilnst". This sorted form is the anagram “key” — use it for grouping and comparison.