Practice · Trie · 1 of 2

Build a Prefix Tree

Write a class Trie (a prefix tree) that stores lowercase words:

  • Trie() makes an empty trie.
  • insert(word) stores word.
  • search(word) returns true if word has been stored, and false otherwise.
  • startsWith(prefix) returns true if some stored word begins with prefix, and false otherwise. A word counts as beginning with itself.

Each test is a list of calls, starting with the constructor; the expected answer lists what each call returns (null for the constructor and for insert).

Example 1

Calls
Trie(), insert("card"), search("car"), startsWith("car"), insert("car"), search("car")
Returns
[null, null, false, true, null, true]
Until "car" is inserted, it is only the start of "card", not a stored word.

Example 2

Calls
Trie(), insert("on"), insert("one"), startsWith("onex"), search("one"), search("o")
Returns
[null, null, null, false, true, false]

Constraints

  • Words and prefixes have 1 to 2000 lowercase English letters.
  • A test makes at most 3 × 10⁴ calls.