Skip to problem
←

Trie Data Structure

Medium 0 attempts

Implement a Trie class that stores words and supports:

  • insert(word): store the word; no return value is required. Reinserting a word leaves it present.
  • search(word): return true only if that complete word was inserted.
  • startsWith(prefix): return true if at least one inserted word begins with the prefix.

A new instance starts empty. State persists across calls in one fixture; each fixture uses a fresh instance. Words and prefixes are nonempty lowercase strings.

After inserting "apple", search("app") is false but startsWith("app") is true. Inserting "app" then makes both searches true without removing "apple".

Function contract

Implement the class Trie. Fixtures contain constructor arguments and a list of [method, ...arguments] calls. Each fixture starts with a fresh instance.

Output: Return the specified result from each method. The displayed output lists results in call order; undefined results appear as null.

Example 1

Input
constructorArgs = []
operations = [["insert","apple"],["search","apple"],["search","app"],["startsWith","app"],["insert","app"],["search","app"]]
Output
[null,true,false,true,null,true]

Example 2

Input
constructorArgs = []
operations = [["search","x"],["startsWith","x"],["insert","x"],["search","x"]]
Output
[false,false,null,true]
Constraints
  • 1 <= word.length, prefix.length <= 2000
  • Words and prefixes contain only lowercase English letters
  • At most 3 * 10^4 calls
Topics

Trie with Object Nodes

Each character follows one child edge. Shared prefixes reuse those edges. Mark the last node of an inserted word with a terminal flag: reaching a node proves that a prefix exists, but search must also check that flag to distinguish a stored word from an unfinished prefix.

The terminal flag uses a key outside the allowed lowercase alphabet, so it cannot collide with a character edge.

javascript
class Trie {
  constructor() { this.root = {}; }
  insert(word) {
    let node = this.root;
    for (const c of word) { if (!node[c]) node[c] = {}; node = node[c]; }
    node.$ = true;
  }
  search(word) {
    let node = this.root;
    for (const c of word) { if (!node[c]) return false; node = node[c]; }
    return !!node.$;
  }
  startsWith(prefix) {
    let node = this.root;
    for (const c of prefix) { if (!node[c]) return false; node = node[c]; }
    return true;
  }
}

Time: O(L) per operation | Space: O(total characters)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript