Skip to content
Commitwise
Menu
Coding Interview

Tries

Store words in a prefix tree to answer "does any word start with this?" in time proportional to the prefix, build autocomplete and wildcard search, and know when a trie beats a hash set or a sorted array, in Swift, Kotlin, Java and TypeScript.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

A search box suggests “swift concurrency” after you type “swi”. A spell checker underlines “recieve”. A router matches /api/users/42 against hundreds of routes. All of them ask the same question many times a second: which stored words start with this prefix? A hash set can only answer “is this exact word stored?”, and scanning a sorted list for every keystroke is wasteful.

A trieTrieA tree that stores words character by character, so all words with the same prefix share one path.Open in glossary → (pronounced “try”, from retrieval) stores words character by character in a tree, so all words with the same prefix share the same path. Looking up a prefix costs only as many steps as the prefix has characters, no matter how many words are stored.

New to some of these? Open what you need, or skip ahead.

Basics:What are lists, sets and maps?

Collections hold many values:

  • A list (Swift Array, Kotlin List, Java List, a TypeScript array) keeps items in order, and allows duplicates: ["Ana", "Ben", "Ana"].
  • A set holds each value at most once and answers “is this in it?” very quickly.
  • A map (Swift Dictionary, Kotlin, Java and TypeScript Map) stores values under keys: "Ana" → 30, looked up by the key.

Lists use indexes starting at 0: in ["a", "b", "c"], "a" is at index 0 and "c" at index 2.

Basics:What is a tree?

A tree is a structure of nodes connected like a family tree: one root at the top, and each node has children below it. A node with no children is a leaf. Following children from the root gives a path. The Trees: DFS and BFS tutorial covers them in depth.

Basics:What does O(n) mean?

Big-O describes how the amount of work grows with the size of the input n:

  • O(1): the same work whatever the size (reading array[5]).
  • O(log n): grows very slowly (about 20 steps for a million items).
  • O(n): grows in step with the input (one pass over the array).
  • O(n²): comparing every item with every other item, which gets slow fast.

You’ll see it next to every solution, for time and for extra space (memory). The Big-O tutorial explains it properly.

Part Not started

A tree of prefixes

Think of a paper dictionary’s thumb index: to find “card”, you open the C section, then look for “ca”, then “car”. Every word starting with “car” sits in the same place.

A trie works the same way. Each node represents a prefix, and its children are the possible next letters:

(root)
 └─ c
     └─ a
         ├─ r   ← "car" ends here
         │   ├─ d   ← "card"
         │   └─ e   ← "care"
         └─ t   ← "cat"

Two things to remember:

  • Each node has a map from character → child node.
  • A node has an isWord flag that says “a word ends here”. The path c → a → r exists for “card” too, but “car” is only a word if its last node is marked.

Inserting or looking up a word of length L walks L nodes: O(L), whether the trie holds ten words or ten million.

A trie (prefix tree) maps each key to a root-to-node path, one edge per symbol, with an end-of-key marker (or a stored value) on the final node. Insert, exact lookup and prefix lookup are O(L) in the key length, independent of the number of keys n, and prefix enumeration is O(L + output). Children are stored as a hash map (any alphabet, more overhead per node), a fixed array (26 for lowercase ASCII: fastest, memory-hungry and sparse), or a sorted array (compact, binary-searched). Space is O(total characters) in the worst case but shared prefixes compress it; radix (compressed) tries merge single-child chains to cut node count, and ternary search trees or DAWGs/FSTs are used when memory matters (Lucene’s term dictionary is an FST). Watch for Unicode: iterate grapheme clusters or code points consistently on insert and lookup.

final class Trie {
    private final class Node {
        var children: [Character: Node] = [:]
        var isWord = false
    }
    private let root = Node()

    func insert(_ word: String) {
        var node = root
        for ch in word {
            if let next = node.children[ch] {
                node = next
            } else {
                let next = Node()
                node.children[ch] = next
                node = next
            }
        }
        node.isWord = true                         // mark where the word ends
    }

    func search(_ word: String) -> Bool { find(word)?.isWord ?? false }
    func startsWith(_ prefix: String) -> Bool { find(prefix) != nil }

    private func find(_ s: String) -> Node? {
        var node = root
        for ch in s {
            guard let next = node.children[ch] else { return nil }
            node = next
        }
        return node
    }
}
class Trie {
    private class Node {
        val children = HashMap<Char, Node>()
        var isWord = false
    }
    private val root = Node()

    fun insert(word: String) {
        var node = root
        for (ch in word) node = node.children.getOrPut(ch) { Node() }
        node.isWord = true                         // mark where the word ends
    }

    fun search(word: String): Boolean = find(word)?.isWord == true
    fun startsWith(prefix: String): Boolean = find(prefix) != null

    private fun find(s: String): Node? {
        var node = root
        for (ch in s) node = node.children[ch] ?: return null
        return node
    }
}
class Trie {
    private static final class Node {
        final Map<Character, Node> children = new HashMap<>();
        boolean isWord;
    }
    private final Node root = new Node();

    void insert(String word) {
        Node node = root;
        for (char ch : word.toCharArray()) {
            node = node.children.computeIfAbsent(ch, c -> new Node());
        }
        node.isWord = true;                        // mark where the word ends
    }

    boolean search(String word) {
        Node node = find(word);
        return node != null && node.isWord;
    }

    boolean startsWith(String prefix) { return find(prefix) != null; }

    private Node find(String s) {
        Node node = root;
        for (char ch : s.toCharArray()) {
            node = node.children.get(ch);
            if (node == null) return null;
        }
        return node;
    }
}
class TrieNode {
  children = new Map<string, TrieNode>();
  isWord = false;
}

class Trie {
  private readonly root = new TrieNode();

  insert(word: string): void {
    let node = this.root;
    for (const ch of word) {
      let next = node.children.get(ch);
      if (!next) {
        next = new TrieNode();
        node.children.set(ch, next);
      }
      node = next;
    }
    node.isWord = true;                            // mark where the word ends
  }

  search(word: string): boolean { return this.find(word)?.isWord ?? false; }
  startsWith(prefix: string): boolean { return this.find(prefix) !== undefined; }

  private find(s: string): TrieNode | undefined {
    let node: TrieNode | undefined = this.root;
    for (const ch of s) {
      node = node.children.get(ch);
      if (!node) return undefined;
    }
    return node;
  }
}
  • insert walks the word letter by letter, creating a child when it’s missing, and marks the last node.
  • find walks a string and returns the node it ends on, or nothing if a letter is missing.
  • search needs that node and its isWord flag; startsWith only needs the node to exist.

Predict the output

A trie contains car, card and care. What do search("ca"), startsWith("ca") and search("car") return?

Spot the bugEvery prefix is a word

Tap the line with the bug.

func search(_ word: String) -> Bool {
    return find(word) != nil
}
fun search(word: String): Boolean {
    return find(word) != null
}
boolean search(String word) {
    return find(word) != null;
}
search(word: string): boolean {
  return this.find(word) !== undefined;
}

Practice: Longest Common Prefix

Exerciseeasy

Longest Common Prefix

Return the longest prefix shared by all strings in the array, or an empty string if there’s none.

["flower", "flow", "flight"]   → "fl"
["dog", "racecar", "car"]      → ""
›

Insert every word into a trie. The common prefix is the path from the root while each node has exactly one child and no word ends there.

›

You can also solve it without a trie: compare characters of the first word with all the others, column by column. Try both and compare.

SolutionTry it yourself firstTime O(total characters)Space O(1) for the column scan

The column scan is shorter and uses no extra memory, so it’s the better answer here; the trie version shines when the same set of words is queried many times.

func longestCommonPrefix(_ words: [String]) -> String {
    guard let first = words.first else { return "" }
    let chars = words.map(Array.init)
    for i in 0..<chars[0].count {
        for word in chars.dropFirst() where i >= word.count || word[i] != chars[0][i] {
            return String(chars[0][..<i])
        }
    }
    return first
}
fun longestCommonPrefix(words: Array<String>): String {
    if (words.isEmpty()) return ""
    val first = words[0]
    for (i in first.indices) {
        for (word in words) {
            if (i >= word.length || word[i] != first[i]) return first.substring(0, i)
        }
    }
    return first
}
String longestCommonPrefix(String[] words) {
    if (words.length == 0) return "";
    String first = words[0];
    for (int i = 0; i < first.length(); i++) {
        for (String word : words) {
            if (i >= word.length() || word.charAt(i) != first.charAt(i)) return first.substring(0, i);
        }
    }
    return first;
}
function longestCommonPrefix(words: string[]): string {
  if (words.length === 0) return "";
  const first = words[0];
  for (let i = 0; i < first.length; i++) {
    for (const word of words) {
      if (i >= word.length || word[i] !== first[i]) return first.slice(0, i);
    }
  }
  return first;
}

Choosing the child representation

Children asLookupMemoryUse when
Hash mapO(1) averageHighest per nodeAny alphabet, sparse nodes
Array of 26O(1), no hashing26 slots per node, mostly emptyLowercase ASCII, interview speed
Sorted arrayO(log k)CompactLarge static dictionaries
Radix trie (merged chains)O(L)Far fewer nodesRouters, IP lookups, long keys with shared prefixes

Trie vs alternatives: a hash set answers exact lookups in O(L) with less memory but can’t enumerate prefixes; a sorted array with binary search finds the range of words with a prefix in O(L log n) and is far more cache-friendly, which often wins for static data. Tries win when there are many prefix queries on a changing set, or when the traversal itself is the algorithm (Word Search II, wildcard matching, longest-prefix match in routing tables).

  • Trie: one edge per symbol, end marker on the last node. Insert, search, startsWith: O(L); enumerate a prefix: O(L + output). Space O(total characters), shared prefixes compress.
  • search needs the end marker; a path only proves a prefix.
  • Children: hash map (any alphabet), array of 26 (fast, sparse), sorted array (compact); radix tries merge single-child chains.
  • Versus a hash set (exact only, smaller) and a sorted array (prefix range by binary search, cache-friendly): use a trie for many prefix queries on changing data, or when traversal drives the algorithm.
  • Unicode: iterate the same unit (characters, code points) on insert and lookup.

Check this part

  1. A trie holds a million words. How many nodes does looking up a 5-letter word visit?

  2. The trie contains only apple. Is app found by search?

  3. For a large static dictionary with prefix queries, what is often faster in practice than a pointer-based trie?

  4. What does a radix (compressed) trie change?

A trie stores each word as a path of characters from the root, with a flag on the node where a word ends. Insert, search and prefix checks cost O(L) for a word of length L, independent of how many words are stored. A word exists only if its last node is marked as an end; a path alone only proves a prefix.

Part Not started

A classic interview version of autocomplete, Search Suggestions System: given a list of products and a search word, after each typed character return up to three products that start with what’s been typed so far, in alphabetical order.

products = ["mobile", "mouse", "moneypot", "monitor", "mousepad"], searchWord = "mouse"
m     → ["mobile", "moneypot", "monitor"]
mo    → ["mobile", "moneypot", "monitor"]
mou   → ["mouse", "mousepad"]
mous  → ["mouse", "mousepad"]
mouse → ["mouse", "mousepad"]

The trick is to do the expensive part once. Sort the products, then insert them into a trie. While inserting, each node along the way keeps a list of up to three words that pass through it. Because the products were inserted in alphabetical order, the first three to pass through a node are its three alphabetically smallest words.

Then each keystroke is just one step down the trie: read that node’s list.

Sort once (O(n log n · L) comparisons), insert while recording the first three words per node (O(total characters)), then answer each of the m prefixes by stepping one node: O(m) after the build. Once a prefix falls off the trie, every longer prefix returns empty. The same structure is how production typeahead stores precomputed top-k per prefix, with popularity instead of alphabetical order.

func suggestedProducts(_ products: [String], _ searchWord: String) -> [[String]] {
    final class Node {
        var children: [Character: Node] = [:]
        var top: [String] = []                     // up to 3 words passing through this node
    }
    let root = Node()
    for product in products.sorted() {
        var node = root
        for ch in product {
            if node.children[ch] == nil { node.children[ch] = Node() }
            node = node.children[ch]!
            if node.top.count < 3 { node.top.append(product) }
        }
    }

    var result: [[String]] = []
    var node: Node? = root
    for ch in searchWord {
        node = node?.children[ch]
        result.append(node?.top ?? [])             // once off the trie, stay off
    }
    return result
}
fun suggestedProducts(products: Array<String>, searchWord: String): List<List<String>> {
    class Node {
        val children = HashMap<Char, Node>()
        val top = ArrayList<String>(3)             // up to 3 words passing through this node
    }
    val root = Node()
    for (product in products.sorted()) {
        var node = root
        for (ch in product) {
            node = node.children.getOrPut(ch) { Node() }
            if (node.top.size < 3) node.top.add(product)
        }
    }

    val result = ArrayList<List<String>>()
    var node: Node? = root
    for (ch in searchWord) {
        node = node?.children?.get(ch)
        result.add(node?.top ?: emptyList())       // once off the trie, stay off
    }
    return result
}
List<List<String>> suggestedProducts(String[] products, String searchWord) {
    final class Node {
        final Map<Character, Node> children = new HashMap<>();
        final List<String> top = new ArrayList<>(3);    // up to 3 words passing through this node
    }
    String[] sorted = products.clone();
    Arrays.sort(sorted);
    Node root = new Node();
    for (String product : sorted) {
        Node node = root;
        for (char ch : product.toCharArray()) {
            node = node.children.computeIfAbsent(ch, c -> new Node());
            if (node.top.size() < 3) node.top.add(product);
        }
    }

    List<List<String>> result = new ArrayList<>();
    Node node = root;
    for (char ch : searchWord.toCharArray()) {
        node = node == null ? null : node.children.get(ch);
        result.add(node == null ? List.of() : node.top);   // once off the trie, stay off
    }
    return result;
}
function suggestedProducts(products: string[], searchWord: string): string[][] {
  class Node {
    children = new Map<string, Node>();
    top: string[] = [];                            // up to 3 words passing through this node
  }
  const root = new Node();
  for (const product of [...products].sort()) {
    let node = root;
    for (const ch of product) {
      let next = node.children.get(ch);
      if (!next) { next = new Node(); node.children.set(ch, next); }
      node = next;
      if (node.top.length < 3) node.top.push(product);
    }
  }

  const result: string[][] = [];
  let node: Node | undefined = root;
  for (const ch of searchWord) {
    node = node?.children.get(ch);
    result.push(node?.top ?? []);                  // once off the trie, stay off
  }
  return result;
}

TypeScript note

[...products].sort() sorts by UTF-16 code units, which matches alphabetical order for lowercase ASCII like this problem. For real product names in many languages, use localeCompare (or Intl.Collator) and sort once with the same rule you’ll use for display.

Predict the output

With the products above, what does the solution return for searchWord = "mx"?

Design Add and Search Words: addWord(word) and search(pattern), where . matches any single letter ("b.d" matches bad and bed). At a dot, the search branches into every child; elsewhere it follows one edge. Worst case is O(26^dots · L), so patterns with many leading dots are slow, which is worth saying in an interview.

final class WordDictionary {
    private final class Node { var children: [Character: Node] = [:]; var isWord = false }
    private let root = Node()

    func addWord(_ word: String) {
        var node = root
        for ch in word {
            if node.children[ch] == nil { node.children[ch] = Node() }
            node = node.children[ch]!
        }
        node.isWord = true
    }

    func search(_ pattern: String) -> Bool { match(Array(pattern), 0, root) }

    private func match(_ p: [Character], _ i: Int, _ node: Node) -> Bool {
        if i == p.count { return node.isWord }
        if p[i] == "." { return node.children.values.contains { match(p, i + 1, $0) } }
        guard let next = node.children[p[i]] else { return false }
        return match(p, i + 1, next)
    }
}
class WordDictionary {
    private class Node { val children = HashMap<Char, Node>(); var isWord = false }
    private val root = Node()

    fun addWord(word: String) {
        var node = root
        for (ch in word) node = node.children.getOrPut(ch) { Node() }
        node.isWord = true
    }

    fun search(pattern: String): Boolean = match(pattern, 0, root)

    private fun match(p: String, i: Int, node: Node): Boolean {
        if (i == p.length) return node.isWord
        if (p[i] == '.') return node.children.values.any { match(p, i + 1, it) }
        val next = node.children[p[i]] ?: return false
        return match(p, i + 1, next)
    }
}
class WordDictionary {
    private static final class Node { final Map<Character, Node> children = new HashMap<>(); boolean isWord; }
    private final Node root = new Node();

    void addWord(String word) {
        Node node = root;
        for (char ch : word.toCharArray()) node = node.children.computeIfAbsent(ch, c -> new Node());
        node.isWord = true;
    }

    boolean search(String pattern) { return match(pattern, 0, root); }

    private boolean match(String p, int i, Node node) {
        if (i == p.length()) return node.isWord;
        char ch = p.charAt(i);
        if (ch == '.') {
            for (Node child : node.children.values()) if (match(p, i + 1, child)) return true;
            return false;
        }
        Node next = node.children.get(ch);
        return next != null && match(p, i + 1, next);
    }
}
class WordDictionary {
  private readonly root = new TrieNode();

  addWord(word: string): void {
    let node = this.root;
    for (const ch of word) {
      let next = node.children.get(ch);
      if (!next) { next = new TrieNode(); node.children.set(ch, next); }
      node = next;
    }
    node.isWord = true;
  }

  search(pattern: string): boolean { return this.match(pattern, 0, this.root); }

  private match(p: string, i: number, node: TrieNode): boolean {
    if (i === p.length) return node.isWord;
    if (p[i] === ".") return [...node.children.values()].some((child) => this.match(p, i + 1, child));
    const next = node.children.get(p[i]);
    return next !== undefined && this.match(p, i + 1, next);
  }
}

Production puzzles

Predict the output

A dictionary trie with 200,000 English words uses a HashMap per node on the JVM. Roughly how does its memory compare with a HashSet of the same words?

Exercisehard

Word Search II

Given an m × n board of letters and a list of words, return all words that can be formed by sequentially adjacent cells (up, down, left, right), using each cell at most once per word. How would you avoid running a separate grid search for each word?

›

Put all words into a trie, then run one DFS from every cell that walks the board and the trie together.

›

Store the complete word in the node where it ends, and remove it once found; prune trie nodes that have no children left so later searches skip dead branches.

SolutionTry it yourself firstTime O(m · n · 4 · 3^(L−1)) worst caseSpace O(total characters in words)

Build a trie of the words, storing each word in its end node. From each cell, DFS: if the cell’s letter isn’t a child of the current trie node, stop; otherwise move to that child, record and clear its word if present, mark the cell visited (temporarily replace it with #), recurse into the four neighbors, then restore the cell. After returning, if the child node has no children and no word left, remove it from its parent: this pruning makes repeated searches cheap once words are found. One combined search replaces k separate ones, and shared prefixes are explored once.

fun findWords(board: Array<CharArray>, words: Array<String>): List<String> {
    class Node { val children = HashMap<Char, Node>(); var word: String? = null }
    val root = Node()
    for (w in words) {
        var node = root
        for (ch in w) node = node.children.getOrPut(ch) { Node() }
        node.word = w
    }
    val found = ArrayList<String>()

    fun dfs(r: Int, c: Int, parent: Node) {
        val ch = board[r][c]
        val node = parent.children[ch] ?: return
        node.word?.let { found.add(it); node.word = null }          // report each word once
        board[r][c] = '#'
        for ((dr, dc) in listOf(0 to 1, 1 to 0, 0 to -1, -1 to 0)) {
            val nr = r + dr; val nc = c + dc
            if (nr in board.indices && nc in board[0].indices && board[nr][nc] != '#') dfs(nr, nc, node)
        }
        board[r][c] = ch
        if (node.children.isEmpty() && node.word == null) parent.children.remove(ch)   // prune
    }

    for (r in board.indices) for (c in board[0].indices) dfs(r, c, root)
    return found
}

The same structure works in every language; the Kotlin version is shown because the nested function keeps it compact.

  • Autocomplete: sort, insert, keep top-k per node during insert; each keystroke is one step, O(1) per character after the build. Off the trie means empty for all longer prefixes.
  • Wildcards: DFS into every child at .; worst case O(alphabet^dots · L).
  • Word Search II: one DFS over board and trie together, store words at end nodes, clear when found, prune empty nodes.
  • Memory: pointer-heavy tries on the JVM cost far more than hash sets; compact representations (arrays, radix, FSTs) in production.

Check this part

  1. In the suggestions solution, why are products sorted before inserting?

  2. After the typed prefix leaves the trie, what is returned for longer prefixes?

  3. Why combine all words into a trie for Word Search II?

  4. What makes wildcard search slow in the worst case?

Autocomplete walks the prefix once, then collects words below that node; storing the top few suggestions in each node during insert makes every keystroke O(L). Wildcard search ('.' matches any letter) branches into every child at a dot with DFS. Pruning the trie while searching, as in Word Search II, keeps grid searches fast.

Key takeaways

  • A trie stores words as paths of characters; words with the same prefix share nodes.
  • Insert, search and prefix checks take time proportional to the word length.
  • A word exists only where it’s marked as ending; a path alone is just a prefix.
  • Autocomplete: do the work at insert time so each keystroke is one step.
  • Choose child representations by alphabet and memory; know radix tries and sorted-array alternatives.
  • Precompute top-k per node for typeahead; branch at wildcards; prune in grid searches.
  • A trie is the right answer when there are many prefix queries on changing data, or when traversal is the algorithm.
  • Be honest about memory: shared prefixes don’t make pointer-heavy tries small.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.