☰ All problems

Implement Trie (Prefix Tree)

A search box suggests completions while the user types. Behind it sits a trie (prefix tree): a tree of letters in which every stored word is a path from the root, so whole words and prefixes can be checked in time proportional to their length.

Implement the Trie class:

  • Trie() creates an empty trie.
  • insert(word) stores word; storing a word that is already present changes nothing.
  • search(word) returns true only if word itself was stored as a complete word.
  • startsWith(prefix) returns true if at least one stored word begins with prefix; every word counts as a prefix of itself.

The tests call the methods one after another.

Example 1
Input: ["Trie","insert","insert","startsWith","search","search","startsWith"]
[[],["sea"],["seal"],["se"],["sea"],["seas"],["seat"]]
Output: [null,null,null,true,true,false,false]

Explanation: Both stored words begin with "se", and "sea" was stored as a word. "seas" was never stored, and no stored word begins with "seat".

Example 2
Input: ["Trie","search","insert","search","startsWith","search"]
[[],["map"],["maple"],["map"],["map"],["maple"]]
Output: [null,false,null,false,true,true]

Explanation: Nothing is found before the first insert. After storing "maple", "map" is only a prefix: startsWith finds it but search does not.

Constraints

  • Every word and prefix is between 1 and 2000 characters long.
  • Words and prefixes use only lowercase English letters.
  • A test makes at most 30,000 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