Implement Trie (Prefix Tree)

Medium#208insert and search

Build a class with three methods: insert(word) adds a word, search(word) says whether exactly this word was added, and startsWith(prefix) says whether some added word begins with these letters. Our calls: insert("top"), insert("tea"), search("to"), startsWith("to"), insert("to"), search("to"), startsWith("tu") — they return false, true, true and false; the inserts return nothing.

input
Calls one after another: Trie() makes an empty trie, then insert(word), search(word) and startsWith(prefix) in any order.
returns
search(word): whether word was inserted; startsWith(prefix): whether an inserted word starts with prefix. insert returns nothing (null in the output).
constraints
  • 2 ≤ calls ≤ 2000
  • 1 ≤ word.length, prefix.length ≤ 50
  • word, prefix: lowercase English letters
our 8 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
var Trie = function() {

};

/**
 * @param {string} word
 * @return {void}
 */
Trie.prototype.insert = function(word) {

};

/**
 * @param {string} word
 * @return {boolean}
 */
Trie.prototype.search = function(word) {

};

/**
 * @param {string} prefix
 * @return {boolean}
 */
Trie.prototype.startsWith = function(prefix) {

};

/**
 * Your Trie object will be instantiated and called as such:
 * var obj = new Trie()
 * obj.insert(word)
 * var param_2 = obj.search(word)
 * var param_3 = obj.startsWith(prefix)
 */
Ctrl ↵
format
reset

saved in this browser

8 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more trie (prefix tree) problems

Pattern “Trie (prefix tree)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.