Two words are said to be anagrams if they have the exact same letters, exact same number of times.
The check for anagram is to sort the letters of both the words and check for equality:
sort_letters(word1) == sort_letters(word2)
Now to find all the anagrams of a given dictionary word say word1
, I would find all the words in the dictionary for which the above test holds. To optimize the search we can just search for words that are of same length.
If we have to do this repeatedly its better to do some preprocessing. We can build something like a HashMap
where in we would map a string
to a set of strings
which are anagrams. Something like:
Bad ==> Dab
Cat ==> Act, Tac
.....
Now given any word I can look into the hashMap
to get all its anagrams.