← Back to Algorithms, page 3

algorithms-0060 · Medium mid

Implement a trie (prefix tree) with insert, search and starts-with, then extend it to count words with a prefix and return autocomplete suggestions.

Each trie node maps a character to a child and has an end flag. Insert walks or creates one node per character and marks the end; search walks and checks the end flag; starts-with only checks that the walk succeeds. All are O(L) for a word of length L. A pass-through counter on each node answers prefix counts in O(L), and a DFS below the prefix node lists suggestions.

Full answer

Problem

Implement Trie with insert(word), search(word) (exact match) and starts_with(prefix). Then add count_prefix(prefix) and words_with_prefix(prefix, limit) for autocomplete.

Example: after inserting apple, app, apply, bat, bath, search("app") is True, search("ap") is False, starts_with("ap") is True, count_prefix("app") is 3, and suggestions for app are ["app", "apple", "apply"].

Constraints: up to 3 * 10^4 operations, words of length 1 to 2,000, lowercase letters.

Brute force

Keep a list (or set) of words. Exact search is O(1) with a set, but starts-with and prefix counting scan every word: O(N * L) per query.

A sorted list with binary search answers prefix queries in O(L log N) but costs O(N) per insert.

Optimal approach

A tree of nodes, each with children: dict[char, node], end: bool and count: int (words passing through).

  • insert: walk from the root, creating missing children, incrementing count; mark end at the last node. Skip if the word already exists so counts stay correct.
  • search: walk; return end of the final node, or False if a child is missing.
  • starts_with: walk; True if every character exists.
  • words_with_prefix: walk to the prefix node, then DFS in sorted child order, collecting words until the limit.

Why it works

All words sharing a prefix share the same path from the root, so the node reached by a prefix represents exactly the set of words with that prefix. The end flag separates "app is a word" from "app is only a prefix of apple". The pass-through count at a node equals the number of distinct inserted words below it.

Complexity

insert, search, starts_with, count_prefix: O(L). Suggestions: O(L + size of the explored subtree). Space: O(total characters inserted) nodes in the worst case, less when prefixes are shared.

Code

python
import random


class TrieNode:
    __slots__ = ("children", "end", "count")

    def __init__(self):
        self.children = {}
        self.end = False                 # a word ends here
        self.count = 0                   # words passing through here (for prefix counts)


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

    def insert(self, word):
        if self.search(word):
            return                       # keep counts correct on duplicate inserts
        node = self.root
        node.count += 1
        for ch in word:
            node = node.children.setdefault(ch, TrieNode())
            node.count += 1
        node.end = True

    def _walk(self, s):
        node = self.root
        for ch in s:
            node = node.children.get(ch)
            if node is None:
                return None
        return node

    def search(self, word):
        node = self._walk(word)
        return bool(node and node.end)

    def starts_with(self, prefix):
        return self._walk(prefix) is not None

    def count_prefix(self, prefix):
        node = self._walk(prefix)
        return node.count if node else 0

    def words_with_prefix(self, prefix, limit=10):
        """Autocomplete: DFS in sorted order below the prefix node."""
        node, out = self._walk(prefix), []
        if node is None:
            return out
        stack = [(node, prefix)]
        while stack and len(out) < limit:
            n, s = stack.pop()
            if n.end:
                out.append(s)
            for ch in sorted(n.children, reverse=True):
                stack.append((n.children[ch], s + ch))
        return out


if __name__ == "__main__":
    t = Trie()
    for w in ("apple", "app", "apply", "bat", "bath"):
        t.insert(w)
    t.insert("app")
    assert t.search("app") and t.search("apple") and not t.search("ap")
    assert t.starts_with("ap") and not t.starts_with("c")
    assert t.count_prefix("app") == 3 and t.count_prefix("ba") == 2 and t.count_prefix("") == 5
    assert t.words_with_prefix("app") == ["app", "apple", "apply"]
    assert t.words_with_prefix("z") == []
    rng = random.Random(60)
    words = {"".join(rng.choice("abc") for _ in range(rng.randint(1, 5))) for _ in range(200)}
    t2 = Trie()
    for w in words:
        t2.insert(w)
    for _ in range(500):
        q = "".join(rng.choice("abc") for _ in range(rng.randint(0, 5)))
        assert t2.search(q) == (q in words)
        assert t2.count_prefix(q) == sum(w.startswith(q) for w in words)
    print("all tests passed")

Save as b60_trie.py and run python3 b60_trie.py. It prints all tests passed (Python 3.13.5).

Edge cases

Duplicate inserts (do not double-count). Empty prefix (matches every word). A word that is a prefix of another (app and apple). Very long words. Deletion needs decrementing counts and pruning empty nodes.

Pattern

Prefix tree for shared-prefix queries. Tries power autocomplete, word search on a board (prune DFS by prefix), IP routing tables (longest prefix match on bits), and the maximum XOR pair problem with a binary trie.

python
import random


class TrieNode:
    __slots__ = ("children", "end", "count")

    def __init__(self):
        self.children = {}
        self.end = False                 # a word ends here
        self.count = 0                   # words passing through here (for prefix counts)


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

    def insert(self, word):
        if self.search(word):
            return                       # keep counts correct on duplicate inserts
        node = self.root
        node.count += 1
        for ch in word:
            node = node.children.setdefault(ch, TrieNode())
            node.count += 1
        node.end = True

    def _walk(self, s):
        node = self.root
        for ch in s:
            node = node.children.get(ch)
            if node is None:
                return None
        return node

    def search(self, word):
        node = self._walk(word)
        return bool(node and node.end)

    def starts_with(self, prefix):
        return self._walk(prefix) is not None

    def count_prefix(self, prefix):
        node = self._walk(prefix)
        return node.count if node else 0

    def words_with_prefix(self, prefix, limit=10):
        """Autocomplete: DFS in sorted order below the prefix node."""
        node, out = self._walk(prefix), []
        if node is None:
            return out
        stack = [(node, prefix)]
        while stack and len(out) < limit:
            n, s = stack.pop()
            if n.end:
                out.append(s)
            for ch in sorted(n.children, reverse=True):
                stack.append((n.children[ch], s + ch))
        return out


if __name__ == "__main__":
    t = Trie()
    for w in ("apple", "app", "apply", "bat", "bath"):
        t.insert(w)
    t.insert("app")
    assert t.search("app") and t.search("apple") and not t.search("ap")
    assert t.starts_with("ap") and not t.starts_with("c")
    assert t.count_prefix("app") == 3 and t.count_prefix("ba") == 2 and t.count_prefix("") == 5
    assert t.words_with_prefix("app") == ["app", "apple", "apply"]
    assert t.words_with_prefix("z") == []
    rng = random.Random(60)
    words = {"".join(rng.choice("abc") for _ in range(rng.randint(1, 5))) for _ in range(200)}
    t2 = Trie()
    for w in words:
        t2.insert(w)
    for _ in range(500):
        q = "".join(rng.choice("abc") for _ in range(rng.randint(0, 5)))
        assert t2.search(q) == (q in words)
        assert t2.count_prefix(q) == sum(w.startswith(q) for w in words)
    print("all tests passed")

Dict-based trie with end flags, pass-through counts and sorted autocomplete; random words are checked against a set and a startswith count.

Complexity

Time: O(L) per operation. Space: O(total characters). A fixed 26-slot array per node is faster in some languages but uses more memory for sparse alphabets.

By level

Fresher: Implements insert, search and starts_with with a dict per node and explains the end flag with an example. States O(L) per operation.

Mid: Adds prefix counts and autocomplete, handles duplicate inserts, and discusses array versus dict children. Implements delete with pruning.

Senior: Discusses radix trees, top-k suggestions cached at nodes, ranking by frequency, and memory limits for millions of words. Compares a trie with a sorted array plus binary search for read-heavy workloads.

Key points

  • Node = children map + end flag
  • Shared prefixes share one path
  • search checks end, starts_with does not
  • Pass-through counts answer prefix counts in O(L)
  • Autocomplete = walk to prefix node then DFS

Common mistakes

  • Returning True from search for a prefix that is not a full word
  • Double-counting duplicate inserts
  • Allocating 26-element arrays for a huge Unicode alphabet
  • Deleting nodes still used by other words

Follow-ups

  • How would you implement delete?
  • How would you rank suggestions by popularity?
  • How do you reduce memory (compressed trie, radix tree)?

Tips

  • Define the node fields first
  • Show the difference between search and starts_with with app and apple
  • Mention memory trade-offs

Evaluation rubric

  • Correct insert, search, starts_with
  • Correct prefix counts
  • Working autocomplete
  • Discusses memory