iq.lab
Python starts when a code cell comes near or you run one
mediumTrie (prefix tree)Design as coding target 25 min

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) stores word. Storing a word twice is the same as storing it once.
  • search(word) answers True exactly when word itself is one of the stored words. A prefix of a stored word does not count: after storing "cart", search("car") is False.
  • starts_with(prefix) answers True exactly when at least one stored word begins with prefix. A stored word begins with itself.

Each Trie() you create starts empty and keeps its own words.

Example 1
Inputinsert("cat"), insert("car"), search("car"), search("ca"), starts_with("ca")OutputTrue, False, True

These are the answers to the three questions, in order. "ca" begins both stored words, but it was never stored itself.

Example 2
Inputinsert("car"), search("cart"), starts_with("cart"), insert("cart"), search("cart"), search("car")OutputFalse, False, True, True

Nothing stored begins with "cart" until it is inserted. Inserting "cart" keeps "car" stored.

Example 3
Inputinsert("go"), insert("go"), search("go"), starts_with("g"), search("g")OutputTrue, True, False

Storing "go" twice changes nothing. "g" begins "go" but is not a stored word.

Constraints
  • 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.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.