Library

Volume 3 · Coding Problems & Data Structures

Notebook
Sign in

Section 23

Trie / Autocomplete (Full Working Code)

679 words · about 3 min

Concept: A tree where each path from root to a marked node spells a word. Enables O(k) prefix search regardless of dictionary size (k = length of the prefix).

Python Implementation

class TrieNode:
    __slots__ = ['children', 'is_end', 'count']

    def __init__(self):
        self.children: dict[str, "TrieNode"] = {}
        self.is_end = False
        self.count = 0  # frequency, for ranking suggestions


class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word: str, count: int = 1) -> None:
        node = self.root
        for char in word:
            node = node.children.setdefault(char, TrieNode())
        node.is_end = True
        node.count += count

    def search(self, word: str) -> bool:
        node = self._find_node(word)
        return node is not None and node.is_end

    def starts_with(self, prefix: str) -> bool:
        return self._find_node(prefix) is not None

    def search_prefix(self, prefix: str, top_k: int = 5) -> list[str]:
        node = self._find_node(prefix)
        if node is None:
            return []
        results: list[tuple[str, int]] = []
        self._dfs(node, prefix, results)
        results.sort(key=lambda x: -x[1])
        return [word for word, _ in results[:top_k]]

    def _find_node(self, prefix: str):
        node = self.root
        for char in prefix:
            if char not in node.children:
                return None
            node = node.children[char]
        return node

    def _dfs(self, node: TrieNode, current: str, results: list) -> None:
        if node.is_end:
            results.append((current, node.count))
        for char, child in node.children.items():
            self._dfs(child, current + char, results)


# --- Usage ---
trie = Trie()
for word, freq in [("cat", 5), ("car", 3), ("card", 8), ("care", 2)]:
    trie.insert(word, freq)
print(trie.search_prefix("car", top_k=2))  # ['card', 'cat'] order by freq

C# Implementation

using System;
using System.Collections.Generic;
using System.Linq;

public class TrieNode
{
    public Dictionary<char, TrieNode> Children { get; } = new();
    public bool IsEnd { get; set; }
    public int Count { get; set; }
}

public class Trie
{
    private readonly TrieNode _root = new();

    public void Insert(string word, int count = 1)
    {
        var node = _root;
        foreach (var c in word)
        {
            if (!node.Children.TryGetValue(c, out var next))
            {
                next = new TrieNode();
                node.Children[c] = next;
            }
            node = next;
        }
        node.IsEnd = true;
        node.Count += count;
    }

    public bool Search(string word)
    {
        var node = FindNode(word);
        return node is { IsEnd: true };
    }

    public bool StartsWith(string prefix) => FindNode(prefix) != null;

    public List<string> SearchPrefix(string prefix, int topK = 5)
    {
        var node = FindNode(prefix);
        if (node == null) return new List<string>();

        var results = new List<(string Word, int Count)>();
        Dfs(node, prefix, results);
        return results.OrderByDescending(r => r.Count)
                       .Take(topK)
                       .Select(r => r.Word)
                       .ToList();
    }

    private TrieNode? FindNode(string prefix)
    {
        var node = _root;
        foreach (var c in prefix)
        {
            if (!node.Children.TryGetValue(c, out var next)) return null;
            node = next;
        }
        return node;
    }

    private void Dfs(TrieNode node, string current, List<(string, int)> results)
    {
        if (node.IsEnd) results.Add((current, node.Count));
        foreach (var (c, child) in node.Children)
            Dfs(child, current + c, results);
    }
}

Complexity

Operation Time Space
Insert / Search / StartsWith O(k) O(ALPHABET_SIZE × N × k) worst case
Prefix suggestions (top-K) O(nodes in subtree) O(matches)

Follow-up: For production autocomplete at scale (e.g., search-engine query suggestions), a plain trie is memory-hungry. Use a compressed trie (radix tree) to merge single-child chains, or precompute top-K suggestions per node at insert time (instead of DFS on every query) to make search_prefix O(k) instead of O(subtree size).