Implement Trie (Prefix Tree)

MediumTries

Build a Trie class, a tree of letters for storing words, with three methods:

insert(word) adds word. search(word) returns true if word itself was inserted, and false otherwise. startsWith(prefix) returns true if some inserted word begins with prefix.

Each test makes a new Trie and calls its methods in order. The output lists what each call returns, with null for the constructor and for insert.

Examples

Example 1
Input:  Trie(), insert("code"), search("code"), search("cod"), startsWith("cod"), insert("cod"), search("cod")
Output: [null, null, true, false, true, null, true]

cod is only a prefix until it is inserted as a word of its own.

Example 2
Input:  Trie(), startsWith("a"), insert("a"), startsWith("a"), search("ab")
Output: [null, false, null, true, false]

Nothing starts with a until a is inserted, and ab never is.

Constraints

  • 1 ≤ word.length, prefix.length ≤ 2000
  • Words and prefixes use lowercase English letters only.
  • At most 3 × 10⁴ calls in all.

Stuck?

Hint 1

Give each node a map from a letter to its child, and a flag that says whether a word ends there.

Hint 2

search and startsWith walk the same path. They differ only in whether the last node must end a word.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 8 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur