Prefix Tree Supporting Insert, Exact Search and Prefix Queries
NielsenSoftware Engineer · OtherLast updated
A coding problem that processes a sequence of insert, exact-match search and prefix-check operations on lowercase words and returns the boolean answers to the queries in order. It tests building a character-level word index and correctly separating whole-word matches from words that are only prefixes of others.
Build a word index over lowercase English words that supports three operations, applied in the order given:
["insert", w]: add the wordwto the index["search", w]: report whether the wordwitself has been inserted["prefix", p]: report whether at least one inserted word starts withp
Process a list of such operations and return the answers to the search and prefix operations, in the order those operations appear.
Function Signature
def run_word_index(operations: List[List[str]]) -> List[bool]:
Rules
- The index starts empty.
- Each operation is a two-element list: the operation name, then a word or prefix.
insertproduces no answer. Inserting a word that is already present changes nothing.searchis true only for an exact match of a previously inserted word; being a prefix of an inserted word is not enough.prefixis true when some inserted word starts withp, including a word equal top.- Each operation sees only the words inserted before it.
- Return an empty list when there are no
searchorprefixoperations.
Constraints
1 <= len(operations) <= 2 * 10^4- Every operation name is one of
"insert","search","prefix" - Every word and prefix has length between 1 and 100 and contains only the lowercase letters
atoz
Examples
Example 1
operations = [["insert", "card"], ["search", "car"], ["prefix", "car"],
["insert", "car"], ["search", "car"], ["search", "cards"]]
output = [False, True, True, False]
Before "car" is inserted it is only a prefix of "card", so the exact search fails while the prefix check succeeds. After the second insert the exact search succeeds, and "cards" was never inserted.
Example 2
operations = [["prefix", "a"], ["insert", "a"], ["prefix", "a"],
["search", "a"], ["search", "ab"]]
output = [False, True, True, False]
Example 3
operations = [["insert", "x"]]
output = []
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.