Build a class WordIndex that stores words and answers two kinds of question about them.
insert(word)addswordto the index. Inserting the same word again changes nothing.search(word)returnstrueif exactlywordwas inserted before, andfalseotherwise.startsWith(prefix)returnstrueif at least one inserted word begins withprefix, andfalseotherwise. A word counts as beginning with itself, so after inserting"card",startsWith("card")istrue.
Constraints:
- Every word and prefix is 1 to 30 lowercase English letters (
atoz). - There can be up to 20,000 inserts and 20,000 calls to
searchandstartsWithin total, in any order. Each call must stay fast, no matter how many words are stored. - A new index is empty. Every
searchandstartsWithreturnsfalseuntil something is inserted.
Input: insert("card"), insert("care"), search("car"), startsWith("car"), insert("car"), search("car")
Output: undefined, undefined, false, true, undefined, true"car" is only the start of other words until it is inserted itself.
Input: insert("go"), startsWith("gone"), search("g")
Output: undefined, false, false