Skip to lesson

Tries power advanced text algorithms including autocomplete engines, grid word search with backtracking, and longest prefix routers.

Building an interactive autocomplete engine

Autocomplete suggests the words that start with the prefix typed so far, found by walking to the prefix node in a trie and collecting the words below it.

Search engines and mobile keyboards suggest query completions as users type individual characters. A naive scan across a dictionary takes linear time proportional to all stored words. An autocomplete trie retrieves matching recommendations in milliseconds.

Example 1 · Brute force: scan every word, O(N * L) time per query, O(1) extra space

Main.javaJava
import java.util.*;
public class Main {    public static void main(String[] args) {        String[] words = {"car", "card", "care", "cat", "dog", "door"};        String prefix = "car";        List<String> found = new ArrayList<>();        for (String w : words) {                          // checks every stored word            if (w.startsWith(prefix)) found.add(w);        }        System.out.println(found);    }}
Output
[car, card, care]

What this code does

  • The loop tests every stored word against the prefix, even words that start with a different letter.
  • With N words of length L, one query costs about N * L character comparisons.
  • A trie jumps straight to the prefix node, so words that do not match are never touched.

Example 2 · Optimal: trie, O(P + matches) time per query

Main.javaJava
import java.util.*;
public class Main {    static class TrieNode {        Map<Character, TrieNode> children = new HashMap<>();        boolean isWord = false;    }
    static class AutocompleteSystem {        TrieNode root = new TrieNode();
        void insert(String word) {            TrieNode cur = root;            for (char c : word.toCharArray()) {                cur = cur.children.computeIfAbsent(c, k -> new TrieNode());            }            cur.isWord = true;        }
        List<String> getSuggestions(String prefix) {            List<String> results = new ArrayList<>();            TrieNode cur = root;            for (char c : prefix.toCharArray()) {                cur = cur.children.get(c);                if (cur == null) return results;            }            dfs(cur, new StringBuilder(prefix), results);            return results;        }
        void dfs(TrieNode node, StringBuilder path, List<String> results) {            if (node.isWord) results.add(path.toString());            for (char c : node.children.keySet()) {                path.append(c);                dfs(node.children.get(c), path, results);                path.deleteCharAt(path.length() - 1);            }        }    }
    public static void main(String[] args) {        AutocompleteSystem ac = new AutocompleteSystem();        ac.insert("cat");        ac.insert("cater");        ac.insert("camera");        ac.insert("dog");
        System.out.println("Suggestions for 'cat': " + ac.getSuggestions("cat"));        System.out.println("Suggestions for 'cam': " + ac.getSuggestions("cam"));    }}
Output
Suggestions for 'cat': [cat, cater]
Suggestions for 'cam': [camera]

What this code does

  • getSuggestions walks down to the node matching the prefix string.
  • dfs explores all descendant paths from that node to gather complete words.
  • Words sharing the prefix are returned cleanly.
  • It is faster because the walk follows only the P characters of the prefix, so unrelated words are never visited.

To fetch suggestions for prefix P, navigate the trie down to the node representing P. If the prefix path is absent, no matching words exist. From the prefix node, launch a depth-first search to harvest all descendant words where isWord is true. In production systems, nodes cache their top-k most frequent descendant queries directly. This pre-computed caching answers prefix queries in O(P + k) time without searching the full subtree.

Word search II: combining trie with grid backtracking

Finding all dictionary words present on an M by N letter board is a classic search problem. Running separate grid depth-first searches for each dictionary word causes massive redundant work. Combining a trie with grid backtracking checks all dictionary words in a single unified traversal.

Example 3 · Word Search II with Trie Pruning

Main.javaJava
import java.util.*;
public class Main {    static class TrieNode {        TrieNode[] next = new TrieNode[26];        String word = null;    }
    static void insert(TrieNode root, String w) {        TrieNode cur = root;        for (char c : w.toCharArray()) {            int i = c - 'a';            if (cur.next[i] == null) cur.next[i] = new TrieNode();            cur = cur.next[i];        }        cur.word = w;    }
    static List<String> findWords(char[][] board, String[] words) {        TrieNode root = new TrieNode();        for (String w : words) insert(root, w);
        List<String> res = new ArrayList<>();        int m = board.length, n = board[0].length;        for (int r = 0; r < m; r++) {            for (int c = 0; c < n; c++) {                dfs(board, r, c, root, res);            }        }        return res;    }
    static void dfs(char[][] board, int r, int c, TrieNode node, List<String> res) {        if (r < 0 || r >= board.length || c < 0 || c >= board[0].length) return;        char ch = board[r][c];        if (ch == '#' || node.next[ch - 'a'] == null) return;
        node = node.next[ch - 'a'];        if (node.word != null) {            res.add(node.word);            node.word = null; // Avoid duplicates        }
        board[r][c] = '#';        dfs(board, r + 1, c, node, res);        dfs(board, r - 1, c, node, res);        dfs(board, r, c + 1, node, res);        dfs(board, r, c - 1, node, res);        board[r][c] = ch;    }
    public static void main(String[] args) {        char[][] board = {            {'o', 'a', 'a', 'n'},            {'e', 't', 'a', 'e'},            {'i', 'h', 'k', 'r'},            {'i', 'f', 'l', 'v'}        };        String[] words = {"oath", "pea", "eat", "rain"};        List<String> found = findWords(board, words);        Collections.sort(found);        System.out.println("Found words: " + found);    }}
Output
Found words: [eat, oath]

What this code does

  • Trie pre-indexes all search dictionary words.
  • Grid backtracking navigates the board and trie concurrently.
  • Invalid prefixes prune branches immediately, speeding up search.

First, insert all dictionary words into a trie in linear preprocessing time. Next, start backtracking from every board cell while advancing along the trie simultaneously. If the current cell character is not a valid child in the active trie node, backtrack immediately. This early pruning eliminates dead ends before exploring millions of invalid grid paths. When reaching a node marked as a valid word, collect it and continue exploring deeper.

Real world search suggestions and prefix routing

Search engines serve millions of autocomplete keystroke suggestions per second. Tries with frequency weights prioritize top-ranked queries with minimal latency overhead.

Example 4 · Longest Common Prefix Finder

Main.javaJava
public class Main {    static class TrieNode {        TrieNode[] next = new TrieNode[26];        int branches = 0;        boolean isWord = false;    }
    static void add(TrieNode root, String s) {        TrieNode cur = root;        for (char c : s.toCharArray()) {            int i = c - 'a';            if (cur.next[i] == null) {                cur.next[i] = new TrieNode();                cur.branches++;            }            cur = cur.next[i];        }        cur.isWord = true;    }
    static String longestCommonPrefix(String[] strs) {        if (strs == null || strs.length == 0) return "";        TrieNode root = new TrieNode();        for (String s : strs) {            if (s.isEmpty()) return "";            add(root, s);        }
        StringBuilder sb = new StringBuilder();        TrieNode cur = root;        while (cur.branches == 1 && !cur.isWord) {            for (int i = 0; i < 26; i++) {                if (cur.next[i] != null) {                    sb.append((char) ('a' + i));                    cur = cur.next[i];                    break;                }            }        }        return sb.toString();    }
    public static void main(String[] args) {        String[] arr1 = {"interspecies", "interstellar", "interstate"};        System.out.println("LCP: " + longestCommonPrefix(arr1));    }}
Output
LCP: inters

What this code does

  • Words are loaded into the trie.
  • Traversal follows the unique single-branch path starting from root.
  • When branches diverge or a word finishes, prefix matching ends.

Network routers match destination IP addresses against routing tables using longest prefix match. Binary bit-tries (Radix trees) inspect address bits sequentially to select correct network interfaces. Bioinformatics tools match genetic sequences against reference genomes using suffix tries.

Next step

Check your understanding

10 quick questions