☰ All problems

47. Implement Trie (Prefix Tree)

A trie (prefix tree) stores a set of strings so that words and prefixes can be looked up in time proportional to their length. It powers features like autocomplete and spell checking.

Implement the Trie class:

  • Trie() creates an empty trie.
  • insert(word) adds word to the trie. Inserting the same word twice has no extra effect.
  • search(word) returns true only if word was inserted as a whole word.
  • startsWith(prefix) returns true if some inserted word begins with prefix. A word counts as a prefix of itself.

Tests call the methods in sequence.

Example 1
Input: ["Trie","insert","search","search","startsWith","insert","search"]
[[],["card"],["card"],["car"],["car"],["car"],["car"]]
Output: [null,null,true,false,true,null,true]

Explanation: After inserting "card", the string "car" is only a prefix, so search("car") is false while startsWith("car") is true. Once "car" is inserted as a word, search("car") becomes true.

Constraints

  • 1 <= word.length, prefix.length <= 2000
  • word and prefix consist only of lowercase English letters
  • At most 3 * 10^4 calls in total
💡 Hint 1

Each node represents a prefix, and each edge adds one letter. The root is the empty prefix.

💡 Hint 2

Give each node up to 26 children (an array or a map) and a flag saying whether a word ends exactly here.

💡 Hint 3

search and startsWith walk the same path; they only differ in whether the final node must carry the end-of-word flag.

class Trie {
  constructor() {

  }

  /** @param {string} word */
  insert(word) {

  }

  /**
   * @param {string} word
   * @return {boolean}
   */
  search(word) {

  }

  /**
   * @param {string} prefix
   * @return {boolean}
   */
  startsWith(prefix) {

  }
}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc