<AI/>
enru
Все статьи

Implement Trie (prefix tree)

LeetCode 208: Implement a prefix tree with insert, search and startsWith operations using recursion.

Сложность
Средняя
Автор
Denis Kolpakov
Опубликовано
Темы
#tree#hash table#trie
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

Implement the interface of a prefix tree:

  • insert(word: string): inserts a word into the tree
  • search(word: string): boolean: checks whether the word is in the tree
  • startsWith(prefix: string): boolean: checks whether any word in the tree starts with the prefix

You can read about prefix trees in the Wikipedia article.

Constraints

  • Words and prefixes have from 1 to 2000 characters
  • Words and prefixes consist only of lowercase English letters
  • At most 30000 calls are made in a test

Example

typescript
const tree = new Trie();
 
tree.insert('apple');
tree.search('apple'); // return true
tree.search('app'); // return false
tree.startsWith('app'); // return true
tree.insert('app');
tree.search('app'); // return true

Solution

To solve this problem you need to know what a prefix tree is and how to work with recursion (to insert values and traverse the tree).

A tree node looks like this:

typescript
class Trie {
  children: Map<string, Trie>;
  isFullWord: boolean;
}

Each node of the prefix tree (except the root) represents a letter. We don't need to store the letter itself in the node, since it is the key in the parent's map of children.

The isFullWord property is a flag that shows whether the current node ends a word.

children is a hash map with links from the current node to its child nodes. The key is a letter (the value of the child node).

So if we put the words acid, ai, aid, aide, aim and air into our structure, we get the following:

end of a word (isFullWord) root a c i "ai" i d "aid" m "aim" r "air" d "acid" e "aide"

To insert a word into the prefix tree, we implement a recursive method.

typescript
insert(word: string): void {
  if (word.length === 0) {
    this.isFullWord = true;
    return;
  }
 
  let child = this.children.get(word[0]);
 
  if (!child) {
    child = new Trie();
    this.children.set(word[0], child);
  }
 
  child.insert(word.slice(1));
}

search and startsWith differ only in that for search the last node of the prefix must have isFullWord set to true. So to implement both of them we can use a simple recursive helper that traverses the tree.

The final solution:

typescript
export class Trie {
  children: Map<string, Trie>;
  isFullWord: boolean;
 
  constructor(children?: Map<string, Trie>, isFullWord?: boolean) {
    this.children = children ?? new Map();
    this.isFullWord = isFullWord ?? false;
  }
 
  insert(word: string): void {
    if (word.length === 0) {
      this.isFullWord = true;
      return;
    }
 
    let child = this.children.get(word[0]);
 
    if (!child) {
      child = new Trie();
      this.children.set(word[0], child);
    }
 
    child.insert(word.slice(1));
  }
 
  search(word: string): boolean {
    const node = this.traverse(word);
    if (!node) {
      return false;
    }
 
    return node.isFullWord;
  }
 
  startsWith(prefix: string): boolean {
    const node = this.traverse(prefix);
 
    return node !== null;
  }
 
  private traverse(prefix: string): Trie | null {
    if (prefix.length === 0) {
      return this;
    }
 
    const child = this.children.get(prefix[0]);
 
    if (!child) {
      return null;
    }
 
    return child.traverse(prefix.slice(1));
  }
}

Complexity Analysis

Since the task is to implement a data structure, we'll analyze the complexity of insert, search and startsWith.

Time Complexity

insert, search and startsWith rely on the recursive methods insert and traverse. The recursion depth of both equals the length of the word or prefix.

So all 3 methods run in O(n), where n is the length of the word or prefix.

Space Complexity

The methods use recursion whose depth equals the length of the word, so they need O(n) memory for the call stack. Inserting a word also allocates up to n new nodes.