Retrieval: Tries

A Trie (derived from "Retrieval") is a specialized tree-based data structure used to store and search strings in a space-efficient and time-efficient manner. It is also known as a Prefix Tree because every node represents a common prefix of the strings stored within it.


1. The Structure: Shared Nodes

In a Trie, individual characters of a word are stored in nodes. Words that share a common prefix share the same set of nodes until they diverge.


2. Operations and Complexity

The primary advantage of a Trie is that performance is determined by the Length of the Word ($L$), not the total number of words ($N$) in the dataset.

Operation Time Complexity Space Complexity
Insert O(L) O(L * Average Alphabet Size)
Search O(L) O(1)
Prefix Search O(L) O(1)

3. Trie vs. Hash Table

If an interviewer asks for a comparison:

Trie Advantages:

Hash Table Advantages:


4. Implementation (Array-based)

class TrieNode {
  constructor() {
    // Array for 26 lowercase English letters
    this.children = new Array(26).fill(null);
    this.isEndOfWord = false;
  }
}

class Trie {
  constructor() {
    this.root = new TrieNode();
  }

  insert(word) {
    let node = this.root;
    for (const char of word) {
      const idx = char.charCodeAt(0) - 'a'.charCodeAt(0);
      if (!node.children[idx]) {
        node.children[idx] = new TrieNode();
      }
      node = node.children[idx];
    }
    node.isEndOfWord = true;
  }
}

5. Interview Pro-Tips: Space Optimization


Technical Summary

  1. L: The length of the string, which governs all performance.
  2. Prefix: The key to efficient autocomplete and group-based string queries.
  3. isEndOfWord: The marker that distinguishes a prefix from a complete word.
  4. Alphabet Size: The primary driver of memory consumption.