consider the word “catsdogcats”. We have the dictionary: ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
We iterate over the word: catsdogcats and at each iteration, we ask if the prefix is contained in dictionary.
If the prefix is in the dictionary, we recursively call the function on the remaining word (excluding matched prefix)
- is
cin dictionary ? - is
cain dictionary ? - is
catin dictionary ? -> YES call(sdogcats) –[1]
Prefix cat matched so recursively call with sdogcats
- is
sin dictionary ? - is
sdin dictionary ? - ….
- is
sdogcatsin dictionary ? NO
We exhausted the word so we return false. Nothing was matched
Back at the first call, this time we try to match cats
Return to [1]
is
catsin dictionary -> YES recursively call ondogcatsis
din dictionary ?is
doin dictionary ?is
dogin dictionary ? -> YES, recursively call oncatsis
cin dictionary ?is
cain dictionary ?is
catin dictionary ? YES , recursively call(s) –[2]is
sin dictionary ? NO -> word exhausted, return false;
Back at recursive call [2]
- is
catsin dictionary ? YES recursively call(``) i.e. empty string
When we reach empty string, it means whole of string can be constructed using words in dictionary. Hence return true.
Import considerations:
- The dictionary has all the words, which means that
catsdogcatswill match with itself completely. To avoid words matching with themselves, we tell the function to ignore thecatsdogcatsword to avoid matching it with itself. - Also, we can memoize the results since, dictionary remains the same, only target word and ignore word changes.
| |