The problem I'm facing is to create an efficient algorithm that returns the list of words from a fixed word list that can be spelled by using a certain set of letters (this set being the input), with this set having no upper bound (or no useful one at least).
More specifically, this algorithm needs to provide solutions in real time for a constantly augmenting input, though the output can be streamed out slowly as long as the first few output elements come out relatively quickly.
**Note: the input's real augmentation occurs only in the form of adding on to the existing set. When a word is chosen, the LetterStock is depleted of all the letters used and the algorithm is run from scratch again.
The set of possible characters are the 26 standard roman letters. The stock of each letter can be anywhere from 0->infinity (for all intensive purposes) and each letter can only be used once (e.g. a,b,l will not return "ball", though a,bb,d,lll will)
The word list being worked with is constant, so if any pre-calculated hashing solution would be useful to speed up runtime performance, that is an option (though I cannot think of a good way to do this). However, the word list is large (~40,000 elements).
Thus far, the best algorithm I've devised involves iterating through the whole set of words using a copy of the letter stock array and checking each word letter-by-letter, depleting the copy stock and seeing if any letter goes below 0. If so, I move on, if not and I reach the end of the word, I add the word to the solution set. After going through the whole set of words, I start from the beginning again looking for words that I can spell now that 1 or more character have been added to my LetterStock.
// Pass in the string and a copy of the LetterStock 26-entry array
bool canBeSpelled(string str, int *letterStock)
{
for(int i=0; i<str.length; i++)
{
letterStock[str[i]-65]--; // deplete the letter stock for the given letter
if(letterStock[str[i]-65] < 0)
return false;
}
return true;
}
My question thus is: Is this implementation optimal and if not, what is a better one?