Build a prefix tree
A prefix of a word is a piece taken from its start: "c", "ca", "car" and "cart" are the prefixes of "cart". Build a class Trie that stores words and answers two questions about them. Each call must take time that depends only on the length of its word or prefix, not on how many words are stored.
Trie()makes an empty store.insert(word)storesword. Storing a word twice is the same as storing it once.search(word)answersTrueexactly whenworditself is one of the stored words. A prefix of a stored word does not count: after storing"cart",search("car")isFalse.starts_with(prefix)answersTrueexactly when at least one stored word begins withprefix. A stored word begins with itself.
Each Trie() you create starts empty and keeps its own words.
insert("cat"), insert("car"), search("car"), search("ca"), starts_with("ca")OutputTrue, False, TrueThese are the answers to the three questions, in order. "ca" begins both stored words, but it was never stored itself.
insert("car"), search("cart"), starts_with("cart"), insert("cart"), search("cart"), search("car")OutputFalse, False, True, TrueNothing stored begins with "cart" until it is inserted. Inserting "cart" keeps "car" stored.
insert("go"), insert("go"), search("go"), starts_with("g"), search("g")OutputTrue, True, FalseStoring "go" twice changes nothing. "g" begins "go" but is not a stored word.
Every word and prefix has 1 to 2,000 lowercase English letters.
At most 3 × 104 calls in total.
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.